File size: 148,164 Bytes
8c6097b |
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 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 |
# Copyright (c) 2025 Huawei Technologies Co., Ltd. All rights reserved.
import os
import json
import random
import re
import time
import logging
from pathlib import Path
from typing import Dict, Any, List, Optional
import requests
import dateutil.parser
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from dataclasses import dataclass
try:
from config.config import get_config
except ImportError:
import sys
sys.path.append(str(Path(__file__).parent.parent.parent))
from config.config import get_config
# Workspace management is handled directly in the tools
logger = logging.getLogger(__name__)
@dataclass
class MCPToolResult:
"""Standard result format for MCP tools"""
success: bool
data: Any = None
error: str = None
metadata: Dict[str, Any] = None
def to_dict(self) -> Dict[str, Any]:
return {
"success": self.success,
"data": self.data,
"error": self.error,
"metadata": self.metadata or {}
}
class MCPTools:
"""Multi Agent System MCP Tools Implementation"""
def __init__(self, workspace_path: str = None):
self.config = get_config()
self.workspace_path = Path(workspace_path) if workspace_path else Path.cwd()
self.workspace_path.mkdir(exist_ok=True, parents=True)
# Session context for workspace-aware operations
self.session_id = None
self.session_workspace_path = None
self.full_workspace_path = os.path.realpath(self.workspace_path)
if not self.full_workspace_path.endswith(os.sep):
self.full_workspace_path += os.sep
def set_session_context(self, session_id: str, session_workspace_path: str):
"""Set session context for workspace-aware operations"""
self.session_id = session_id
self.session_workspace_path = Path(session_workspace_path)
# Update workspace path to session-specific path
self.workspace_path = self.session_workspace_path
self.full_workspace_path = os.path.realpath(self.workspace_path)
if not self.full_workspace_path.endswith(os.sep):
self.full_workspace_path += os.sep
logger.info(f"Set session context - ID: {session_id}, Workspace: {session_workspace_path}")
def get_session_context(self) -> Dict[str, Any]:
"""Get current session context"""
return {
"session_id": self.session_id,
"session_workspace_path": str(self.session_workspace_path) if self.session_workspace_path else None,
"workspace_path": str(self.workspace_path)
}
def _safe_join(self, path: str) -> Path:
if os.path.isabs(path):
raise Exception(f"Path '{path}' is absolute. Only relative paths are allowed.")
joined_path = os.path.join(self.workspace_path, path)
full_joined_path = os.path.realpath(joined_path)
if not full_joined_path.startswith(self.full_workspace_path):
raise Exception(f"Path '{path}' is outside workspace directory.")
return Path(full_joined_path)
# ================ WEB SEARCH TOOLS ================
def batch_web_search(
self,
queries: List[str],
max_results_per_query: int = 15,
max_workers: int = 5
) -> MCPToolResult:
"""
Batch web search using configurable search provider with concurrent processing.
Users need to implement their own search provider. Below is an example available:
[
{
"query": "search query",
"search_results": [
{
"title": "Page title",
"link": "https://example.com",
"snippet": "Description snippet",
"date": "Feb 8, 2022",
},
...
]
},
...
]
Args:
queries: List of search queries
max_results_per_query: Maximum search results per query
max_workers: Maximum number of concurrent search requests
"""
try:
from config.config import get_search_engine_config
search_config = get_search_engine_config()
if not search_config:
return MCPToolResult(
success=False,
error="Search engine not configured"
)
# Ensure we never return more than 15 results per query
actual_max_results = min(max_results_per_query, 15)
def search_single_query(query: str) -> Dict[str, Any]:
"""Search a single query"""
try:
search_results = self._generic_search(query, actual_max_results, search_config)
if not search_results.success:
return {
'query': query,
'success': False,
'error': search_results.error,
'results': []
}
# Process search results
search_data = search_results.data
search_data["organic"] = search_data["organic"][:actual_max_results]
return {
'query': query,
'success': True,
'results': search_data,
'timestamp': time.time()
}
except Exception as e:
logger.error(f"Error searching query '{query}': {e}")
return {
'query': query,
'success': False,
'error': str(e),
'results': []
}
# Execute searches concurrently
all_results = []
with ThreadPoolExecutor(max_workers=min(max_workers, len(queries))) as executor:
# Submit all search tasks
future_to_query = {executor.submit(search_single_query, query): query for query in queries}
# Collect results as they complete
for future in as_completed(future_to_query):
try:
result = future.result()
all_results.append(result)
except Exception as e:
query = future_to_query[future]
logger.error(f"Error processing search for '{query}': {e}")
all_results.append({
'query': query,
'success': False,
'error': str(e),
'results': []
})
# Sort results to maintain original query order
query_order = {query: i for i, query in enumerate(queries)}
all_results.sort(key=lambda x: query_order.get(x['query'], float('inf')))
return MCPToolResult(
success=True,
data=all_results,
metadata={
'total_queries': len(queries),
'successful_queries': len([r for r in all_results if r.get('success', False)]),
'concurrent_workers': min(max_workers, len(queries))
}
)
except Exception as e:
logger.error(f"Batch web search failed: {e}")
return MCPToolResult(success=False, error=str(e))
def _generic_search(self, query: str, max_results: int, config: Dict[str, Any]) -> MCPToolResult:
"""
Generic search function that users need to implement.
This function should return results in the standard format and be wrapped in MCPToolResult:
search_res = {
"organic": [
{
"title": "Page title",
"link": "https://example.com",
"snippet": "Description snippet",
"date": "Feb 8, 2022"
}
]
}
return MCPToolResult(success=True, data=search_res)
Users should implement their own search logic here based on their preferred search service.
Notes:
1. It is recommended to use search engine APIs that comply with relevant safety and regulatory requirements.
The user assumes full responsibility for any safety issues, legal consequences, or policy violations
arising from the use of the search engine results.
2. User requests may be indirectly transmitted to the search engine API in the form of search queries.
It is the user's responsibility to implement appropriate measures to protect personal privacy and
sensitive information. We assume no liability for privacy-related issues arising from such transmission.
"""
try:
# This is a placeholder - users should implement their own search logic
raise NotImplementedError(
"Generic search provider not implemented. Please implement your own search logic in _generic_search method. "
"The return format should match the standard format with 'organic' results containing title, link, snippet, and date fields."
)
# Example implementation for serper (commented out):
# url = config.get('base_url', 'https://api.search-provider.com/search')
# payload = json.dumps({"q": query, "num": max_results})
# api_keys = config.get('api_keys', [])
# headers = {
# 'X-API-KEY': random.choice(api_keys),
# 'Content-Type': 'application/json'
# }
except Exception as e:
return MCPToolResult(success=False, error=f"Generic search failed: {e}")
@staticmethod
def _extract_publication_date_from_html(url: str) -> Optional[str]:
"""Extract publication date directly from webpage HTML"""
try:
# Fetch HTML content
response = requests.get(url, timeout=10, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
# Common meta tags for publication date
meta_selectors = [
'meta[property="article:published_time"]',
'meta[property="article:modified_time"]',
'meta[name="date"]',
'meta[name="pubdate"]',
'meta[name="published"]',
'meta[name="datePublished"]',
'meta[name="publication-date"]',
'meta[property="og:published_time"]',
'meta[name="DC.date"]',
'meta[name="DC.date.created"]',
'meta[itemprop="datePublished"]',
'meta[itemprop="dateModified"]'
]
for selector in meta_selectors:
meta_tag = soup.select_one(selector)
if meta_tag:
content = meta_tag.get('content') or meta_tag.get('datetime')
if content:
try:
# Parse and standardize the date
parsed_date = dateutil.parser.parse(content)
return parsed_date.isoformat()
except ValueError:
continue
# Check for time tags with datetime attribute
time_tags = soup.find_all('time', {'datetime': True})
for time_tag in time_tags:
try:
parsed_date = dateutil.parser.parse(time_tag['datetime'])
return parsed_date.isoformat()
except ValueError:
continue
# JSON-LD structured data
json_ld_scripts = soup.find_all('script', {'type': 'application/ld+json'})
for script in json_ld_scripts:
try:
data = json.loads(script.string)
if isinstance(data, dict):
date_fields = ['datePublished', 'dateCreated', 'dateModified']
for field in date_fields:
if field in data:
parsed_date = dateutil.parser.parse(data[field])
return parsed_date.isoformat()
elif isinstance(data, list):
for item in data:
if isinstance(item, dict):
for field in date_fields:
if field in item:
parsed_date = dateutil.parser.parse(item[field])
return parsed_date.isoformat()
except ValueError:
continue
return None
except Exception as e:
logger.debug(f"Error extracting publication date from {url}: {e}")
return None
def _content_extractor(self, url: str, max_tokens: int, config: Dict[str, Any]) -> MCPToolResult:
"""Get content using URL content extractor"""
max_retry_num = 5
sleep_time = 5
retry_num = 0
while True:
retry_num += 1
try:
api_key = random.choice(config.get('api_keys', ['default_key']))
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
# Users need to implement this - placeholder for custom URL crawler
raise NotImplementedError(
"URL crawler not implemented. Please implement your own URL crawling logic. "
"The function should extract text content from URLs and return it in a structured format "
"with metadata like title, publication date, and word count."
)
# Example implementation for content extractor (commented out):
# crawler_url = f"{crawler_config.get('base_url', 'https://api.content-extractor.com')}/{url}"
# response = requests.get(crawler_url, headers=headers, timeout=crawler_config.get('timeout', 30))
# response.raise_for_status()
# content = response.text
# # Truncate if needed
# if max_tokens and len(content.split()) > max_tokens:
# words = content.split()[:max_tokens]
# content = ' '.join(words) + '...'
# return MCPToolResult(success=True, data=content)
except Exception as e:
if retry_num == max_retry_num:
return MCPToolResult(success=False, error=f"Content extractor failed: {e}")
else:
time.sleep(sleep_time)
def url_crawler(
self,
documents: List[Dict],
max_tokens_per_url: int = 100000,
include_metadata: bool = True,
max_workers: int = 10
) -> MCPToolResult:
"""
Extract LLM-friendly content from URLs using configurable crawler service.
Content is saved to specified file paths.
Users need to implement their own URL crawler. The return format should include:
- Extracted text content from the URL
- Metadata like title, publication date, word count
- Success/error status for each URL
Args:
documents: List of document dictionaries containing:
- url: Web page URL to extract
- file_path: Local path to save extracted content
- title: (Optional) Web page title
- time: (Optional) Web page publication time
max_tokens_per_url: Maximum tokens per URL result
include_metadata: Whether to include metadata about extraction
max_workers: Maximum number of concurrent extraction requests
"""
try:
from config.config import get_url_crawler_config
crawler_config = get_url_crawler_config()
if not crawler_config:
return MCPToolResult(
success=False,
error="URL crawler not configured"
)
def process_single_document(doc: Dict) -> Dict[str, Any]:
"""Process a single document: extract content and save to file"""
url = doc['url']
file_path = doc['file_path']
title = doc.get('title')
doc_time = doc.get('time')
result_base = {
'url': url,
'file_path': file_path,
'title': title,
'time': doc_time,
'success': False,
'error': None,
'content_length': 0,
'word_count': 0,
'publication_date': None,
'extraction_timestamp': time.time(),
'write_success': False
}
try:
# Extract publication date from the webpage
publication_date = self._extract_publication_date_from_html(url)
result_base["publication_date"] = publication_date
# Extract content using content extractor
content_result = self._content_extractor(url, max_tokens_per_url, crawler_config)
if not content_result.success:
result_base['error'] = content_result.error
return result_base
content = content_result.data
if not content:
result_base['error'] = "Extracted content is empty"
return result_base
# Save content to file
write_result = self.file_write(
file_path=file_path,
content=content,
create_dirs=True
)
if not write_result.success:
result_base['error'] = f"File write failed: {write_result.error}"
return result_base
# Build success result
result = {
**result_base,
'success': True,
'content_length': len(content),
'word_count': len(content.split()),
'publication_date': publication_date,
'write_success': True
}
if include_metadata:
result['metadata'] = {
'truncated': len(content.split()) >= max_tokens_per_url,
'has_publication_date': publication_date is not None,
'date_extraction_method': 'html_parsing' if publication_date else None,
'file_size': len(content.encode('utf-8'))
}
return result
except Exception as e:
logger.error(f"Error processing document {url}: {e}")
# Try to extract publication date even if processing failed
try:
publication_date = self._extract_publication_date_from_html(url)
except:
publication_date = None
return {
**result_base,
'error': str(e),
'publication_date': publication_date
}
# Execute processing concurrently
results = []
with ThreadPoolExecutor(max_workers=min(max_workers, len(documents))) as executor:
# Submit all processing tasks
future_to_doc = {executor.submit(process_single_document, doc): doc for doc in documents}
# Collect results as they complete
for future in as_completed(future_to_doc):
doc = future_to_doc[future]
try:
result = future.result()
results.append(result)
except Exception as e:
url = doc['url']
logger.error(f"Error processing extraction for '{url}': {e}")
# Try to extract publication date even if processing failed
try:
publication_date = self._extract_publication_date_from_html(url)
except:
publication_date = None
results.append({
'url': url,
'file_path': doc['file_path'],
'title': doc.get('title'),
'time': doc.get('time'),
'success': False,
'error': str(e),
'publication_date': publication_date,
'extraction_timestamp': time.time(),
'write_success': False
})
# Sort results to maintain original document order
url_order = {doc['url']: i for i, doc in enumerate(documents)}
results.sort(key=lambda x: url_order.get(x['url'], float('inf')))
successful_extractions = len([r for r in results if r.get('success', False)])
successful_writes = len([r for r in results if r.get('write_success', False)])
return MCPToolResult(
success=True,
data=results,
metadata={
'total_documents': len(documents),
'successful_extractions': successful_extractions,
'successful_writes': successful_writes,
'failed_processing': len(documents) - successful_extractions,
'concurrent_workers': min(max_workers, len(documents))
}
)
except Exception as e:
logger.error(f"URL crawler batch processing failed: {e}")
return MCPToolResult(success=False, error=str(e))
def file_read_dq(self, file_path: str, encoding: str = 'utf-8') -> MCPToolResult:
"""Read file content"""
try:
full_path = self._safe_join(file_path)
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
content = full_path.read_text(encoding=encoding)
if len(content) > 40000:
content = (
"Due to the content being too long, only the first 30,000 and last 10,000 characters are returned.\n"
"Below is the returned portion of the file content:\n\n"
f"First 30,000 characters:\n\n{content[:30000]}\n\n"
f"Last 10,000 characters:\n\n{content[-10000:]}"
)
return MCPToolResult(
success=True,
data=content,
metadata={
'file_size': len(content),
'line_count': len(content.splitlines()),
'encoding': encoding
}
)
except Exception as e:
logger.error(f"File read failed: {e}")
return MCPToolResult(success=False, error=str(e))
def load_json(self, file_path: str, encoding: str = 'utf-8') -> MCPToolResult:
"""
Read JSON format file
"""
try:
full_path = self._safe_join(file_path)
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
res = []
with open(full_path, "r", encoding=encoding, errors='ignore') as f:
for idx, line in enumerate(f):
try:
ele = json.loads(line.strip())
res.append(ele)
except Exception as e:
logger.warning(f"Failed to process file: {e}")
continue
return MCPToolResult(
success=True,
data=res,
metadata={
'line_count': len(res),
'encoding': encoding
}
)
except Exception as e:
logger.error(f"File read failed: {e}")
return MCPToolResult(success=False, error=str(e))
def document_qa(
self,
tasks: List[Dict],
model: str = "pangu_auto",
temperature: Optional[float] = None,
max_tokens: Optional[int] = None,
max_workers: int = 5
) -> MCPToolResult:
"""
Answer questions based on content stored in local files.
Each task contains a file path and a question to be answered using that file's content.
Args:
tasks: List of task dictionaries containing:
- file_path: Relative path to the file (relative to workspace root) to read
- question: Question to ask about this file
model: AI model to use for generating answers
temperature: Creativity level for the AI response (0-1)
max_tokens: Maximum tokens for the AI response
max_workers: Maximum number of concurrent model API requests
"""
try:
# Get configuration
from config.config import get_model_config, get_storage_config
model_config = get_model_config()
storage_config = get_storage_config()
# Use config values or defaults
if temperature is None:
temperature = model_config.get('temperature', 0.3)
if max_tokens is None:
max_tokens = model_config.get('max_tokens', 8192)
logger.debug(f"Starting document QA processing: {tasks}")
# 处理单个任务
def process_single_task(task: Dict) -> Dict:
file_path = task['file_path']
question = task['question']
# 1. 读取文件内容
read_result = self.file_read_dq(file_path)
if not read_result.success:
return {
'file_path': file_path,
'question': question,
'success': False,
'error': f"File read error: {read_result.error}",
'answer': None
}
content = read_result.data
# 2. 构建系统提示
system_prompt = (
"You are an expert document analyst. Answer the user's question "
"based ONLY on the provided context. If the answer cannot be found "
"in the context, say 'I don't know'. Answer in the same language as the user's question. "
"If the document section you reference includes citation sources, such as URLs, you must also include the original citation sources from the document in your response.\n\n"
"CONTEXT:\n{context}"
).format(context=content)
# 3. 调用大模型API
try:
# Get model URL and token from config
# Prefer config over environment variables, with hardcoded fallback
model_url = model_config.get('url') or os.getenv('MODEL_REQUEST_URL', '')
model_token = model_config.get('token') or os.getenv('MODEL_REQUEST_TOKEN', '')
headers = {'Content-Type': 'application/json', 'csb-token': model_token}
response = requests.post(
url=model_url,
headers=headers,
json={
"model": model_config.get('model', 'pangu_auto'),
"chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<s>[unused9]系统:[unused10]' }}{% endif %}{% if message['role'] == 'system' %}{{'<s>[unused9]系统:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'assistant' %}{{'[unused9]助手:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'tool' %}{{'[unused9]工具:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'function' %}{{'[unused9]方法:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'user' %}{{'[unused9]用户:' + message['content'] + '[unused10]'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[unused9]助手:' }}{% endif %}",
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": question+" /no_think"}
],
"spaces_between_special_tokens": False,
"temperature": temperature,
"max_tokens": max_tokens
},
timeout=model_config.get("timeout", 180)
)
response = response.json()
answer = response["choices"][0]["message"]["content"].split("[unused17]")[-1]
return {
'file_path': file_path,
'question': question,
'success': True,
'answer': answer,
'metadata': {
'file_size': len(content),
'line_count': len(content.splitlines())
}
}
except Exception as e:
logger.error(f"Model API call failed for file '{file_path}': {e}")
return {
'file_path': file_path,
'question': question,
'success': False,
'error': f"Model API error: {str(e)}"
}
# 4. 并发处理所有任务
results = []
with ThreadPoolExecutor(max_workers=min(max_workers, len(tasks))) as executor:
future_to_task = {executor.submit(process_single_task, task): task for task in tasks}
for future in as_completed(future_to_task):
try:
result = future.result()
results.append(result)
except Exception as e:
task = future_to_task[future]
logger.error(f"Task processing failed for file '{task['file_path']}': {e}")
results.append({
'file_path': task['file_path'],
'question': task['question'],
'success': False,
'error': f"Task processing exception: {str(e)}"
})
# 5. 保持原始任务顺序
task_order = {task['file_path']: i for i, task in enumerate(tasks)}
results.sort(key=lambda x: task_order.get(x['file_path'], float('inf')))
# 6. 统计结果
successful_tasks = len([r for r in results if r.get('success', False)])
return MCPToolResult(
success=True,
data=results,
metadata={
'total_tasks': len(tasks),
'successful_tasks': successful_tasks,
'failed_tasks': len(tasks) - successful_tasks,
'concurrent_workers': min(max_workers, len(tasks))
}
)
except Exception as e:
logger.error(f"Context-based QA batch processing failed: {e}")
return MCPToolResult(success=False, error=str(e))
def search_result_classifier(
self,
# save_analysis_file_path: str,
outline: str,
key_files: List[Dict],
model: str = "pangu_auto",
temperature: Optional[float] = None,
max_tokens: Optional[int] = None
) -> MCPToolResult:
"""
Classify and organize search result files according to a structured outline for comprehensive long-form content generation.
Args:
outline: Structured outline defining the sections and subsections for organizing the long-form content
key_files: List of key files to classify
model: AI model to use for classification and organization
temperature: Creativity level for the AI classification (0-1)
max_tokens: Maximum tokens for the AI response
"""
try:
# Get configuration
from config.config import get_model_config, get_storage_config
model_config = get_model_config()
storage_config = get_storage_config()
# Use config values or defaults
if temperature is None:
temperature = model_config.get('temperature', 0.3)
if max_tokens is None:
max_tokens = model_config.get('max_tokens', 2000)
logger.debug(f"Starting search result classification: outline={outline}, key_files={key_files}")
key_files_dict = {}
# Create full path relative to workspace using config
analysis_path = storage_config.get('document_analysis_path', './doc_analysis')
file_analysis_list = self.load_json(f"{analysis_path}/file_analysis.jsonl").data
for file_info in file_analysis_list:
if file_info.get('file_path'):
key_files_dict[file_info.get('file_path')] = file_info
prompt_files = ""
if key_files:
prompt_files += f"Key Files with Multi-Dimensional Analysis:\n"
for i, file_info in enumerate(key_files, 1):
if file_info.get('file_path') in key_files_dict:
file_info = key_files_dict[file_info.get('file_path')]
prompt_files += f"\n{i}. File: {file_info.get('file_path', 'Unknown')}\n"
prompt_files += f" Document Time: {file_info.get('doc_time', 'Not specified')}\n"
prompt_files += f" Source Authority: {file_info.get('source_authority', 'Not specified')}\n"
prompt_files += f" Core Content: {file_info.get('core_content', 'Not specified')}\n"
prompt_files += f" Task Relevance: {file_info.get('task_relevance', 'Not specified')}\n"
prompt_files += f" Information Richness: {file_info.get('information_richness', 'Not specified')}\n"
prompt_files += "\n"
prompt_files += "\n"
system_prompt = (
"You are an expert content organizer specializing in multi-dimensional file classification. "
"Your task is to classify research files according to a given outline by according the five key dimensions.\n\n"
"FIVE KEY DIMENSIONS:\n"
"1. DOCUMENT TIME: Consider the temporal relevance and recency of the source\n"
"2. SOURCE AUTHORITY: Consider the credibility and expertise of the source\n"
"3. CORE CONTENT: Focus on the main themes and key insights\n"
"4. TASK RELEVANCE: Assess alignment with the specific research goals\n"
"5. INFORMATION RICHNESS: Determine the information richness of the document\n"
"CLASSIFICATION INSTRUCTIONS:\n"
"1. Read the outline and understand its structure\n"
"2. Analyze each file across the five dimensions provided\n"
"3. Accept files with moderate source authority, moderate information richness and reasonable task relevance\n"
"4. Use core content insights to find connections to outline sections, ensure the relevance of the assignment.\n"
"5. Files should be assigned to multiple sections when they contain information spanning different topics\n"
"6. Prioritize comprehensive coverage: Ensure every paragraph/chapter gets file assignments when any relevant content exists\n"
"7.Note that if the first chapter is an abstract or introduction, a corresponding file must be assigned and there cannot be an empty file.\n"
"CRITICAL REQUIREMENT - OUTLINE STRUCTURE PRESERVATION:\n"
"- The number of files assigned to each chapter cannot exceed 11, so if the number of files exceeds 11, you need the most relevant files.\n"
"- When the outline is divided into paragraphs/sections, you must preserve the original content and structure exactly.\n "
"- Do NOT modify, rephrase, or alter any paragraph titles, headings, or structural elements from the original outline. \n"
"- Keep all outline content completely intact in your output, including formatting and wording.\n"
"- You should split each paragraph according to the granularity of the first-level heading. You are not allowed to separate any second-level headings or smaller headings under the first-level heading into individual paragraphs.\n"
"- Formatting requirements for split paragraphs: 1. You are not allowed to modify the format of the paragraphs in the original outline, including all bold symbols, etc.; 2. If the given outline includes the title of the article, you must include the article title in the first paragraph, maintaining its original bold symbols.\n"
"Strictly follow the following format for output:\n"
"paragraph 1: ...\n"
"file_path_list: file_path1, file_path2, ...\n"
"\n"
"paragraph 2: ...\n"
"file_path_list: file_path3, file_path4, ...\n"
"..."
)
# 构建用户提示 - 仅包含输入数据
user_prompt = f"""
OUTLINE TO ORGANIZE CONTENT:
{outline}
{prompt_files}
"""
# 调用AI模型进行分类
# Get model URL and token from config
config = get_config()
model_config = config.get_custom_llm_config()
model_url = model_config.get('url') or os.getenv('MODEL_REQUEST_URL', '')
model_token = model_config.get('token') or os.getenv('MODEL_REQUEST_TOKEN', '')
headers = {'Content-Type': 'application/json', 'csb-token': model_token}
try:
# Add retry logic for AI model call
max_retries = 5
response = None
for attempt in range(max_retries):
try:
response = requests.post(
url=model_url,
headers=headers,
json={
"model": model_config.get('model', 'pangu_auto'),
"chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<s>[unused9]系统:[unused10]' }}{% endif %}{% if message['role'] == 'system' %}{{'<s>[unused9]系统:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'assistant' %}{{'[unused9]助手:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'tool' %}{{'[unused9]工具:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'function' %}{{'[unused9]方法:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'user' %}{{'[unused9]用户:' + message['content'] + '[unused10]'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[unused9]助手:' }}{% endif %}",
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"}
],
"spaces_between_special_tokens": False,
"max_tokens": max_tokens,
"temperature": temperature,
},
timeout=model_config.get("timeout", 180)
)
response = response.json()
logger.debug(f"API response received")
break # Success, exit retry loop
except Exception as e:
logger.warning(f"LLM API call attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
raise e # Last attempt, re-raise the exception
time.sleep(5) # Simple 1 second delay between retries
if response is None:
raise Exception("Failed to get response after all retries")
# ai_response = response.choices[0].message.content.strip()
ai_response = response["choices"][0]["message"]["content"].strip()
session_context = self.get_session_context()
session_id = session_context.get("session_id")
# 切换保存的方式
conversation_history = [
# {"role": "system", "content": "system 1"},
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"},
{"role": "assistant", "content": ai_response}
]
return MCPToolResult(
success=True,
data=ai_response.split('think>')[-1].strip(),
)
except Exception as e:
logger.error(f"AI model call failed: {e}")
return MCPToolResult(
success=False,
error=f"AI classification failed: {str(e)}"
)
except Exception as e:
logger.error(f"Search result classifier failed: {e}")
return MCPToolResult(success=False, error=str(e))
# 实现section writer的具体内容
@staticmethod
def _correct_title_format(content: str, overall_outline: str) -> str:
"""
Correct title formats in content to match those in overall_outline.
Args:
content: The generated chapter content
overall_outline: The overall outline containing correct title formats
Returns:
Content with corrected title formats
"""
# Extract titles from overall_outline
outline_titles = {}
for line in overall_outline.split('\n'):
line = line.strip()
if line:
# Extract core title content by removing various formatting symbols
core_content = line
# Remove leading symbols like **, -, etc.
core_content = re.sub(r'^[\*\-\s]+', '', core_content)
# Remove trailing symbols like **
core_content = re.sub(r'[\*\s]+$', '', core_content)
core_content = core_content.strip()
if core_content:
# Store mapping from core content to the formatted line from outline
outline_titles[core_content.lower()] = line
# Process content line by line
content_lines = content.split('\n')
corrected_lines = []
for line in content_lines:
original_line = line
line_stripped = line.strip()
# Check if this line is a title (starts with # and typically has ** formatting)
if line_stripped and re.match(r'^#+\s*[\*]*.*', line_stripped):
# Extract core content from the title
core_content = line_stripped
# Remove markdown headers (#)
core_content = re.sub(r'^#+\s*', '', core_content)
# Remove ** formatting
core_content = re.sub(r'^\*\*', '', core_content)
core_content = re.sub(r'\*\*$', '', core_content)
core_content = core_content.strip()
# Look for exact matching title in outline_titles
found_match = False
core_content_lower = core_content.lower()
for outline_core, outline_format in outline_titles.items():
if outline_core == core_content_lower:
# Replace with the correct format from overall_outline
corrected_lines.append(outline_format)
found_match = True
break
if not found_match:
# If no exact match found, keep original line
corrected_lines.append(original_line)
else:
corrected_lines.append(original_line)
return '\n'.join(corrected_lines)
def section_writer(
self,
written_chapters_summary: str,
task_content: str,
user_query: str,
current_chapter_outline: str,
overall_outline: str,
target_file_path: str,
key_files: List[Dict],
model: str = "pangu_auto",
temperature: Optional[float] = None,
max_tokens: Optional[int] = None
) -> MCPToolResult:
"""
Write the current chapter content based on given web information and chapter structure; also consider user questions, completed chapters, and overall outline to ensure content relevance while avoiding duplication or contradictions.
Args:
user_query: The user query, ensure the drafted content is highly relevant to the user's inquiry.
current_chapter_outline: This field represents the current chapter structure to be drafted. When composing the chapter content, do not modify content and bold formatting symbols of the existing structure's titles!!!
overall_outline: This field represents the overall outline of the article. When drafting the chapter content, you should consider the overall outline to ensure the chapter content is consistent with the overall outline.
target_file_path: The path to save the chapter content
key_files: These files are the source materials required for drafting the current chapter.
model: AI model to use for writing the chapter content
temperature: Creativity level for the AI response (0-1)
max_tokens: Maximum tokens for the AI response
"""
try:
# Get configuration
from config.config import get_model_config, get_storage_config
model_config = get_model_config()
storage_config = get_storage_config()
# Use config values or defaults
if temperature is None:
temperature = model_config.get('temperature', 0.3)
if max_tokens is None:
max_tokens = model_config.get('max_tokens', 8192)
key_files_dict = {}
# Create full path relative to workspace using config
analysis_path = storage_config.get('document_analysis_path', './doc_analysis')
file_analysis_list = self.load_json(f"{analysis_path}/file_analysis.jsonl").data
logger.debug("File analysis loaded successfully")
for i, file_info in enumerate(file_analysis_list, 1):
file_info['index'] = i # 在这里给网页进行编号, 从1开始
if file_info.get('file_path'):
key_files_dict[file_info.get('file_path')] = file_info
prompt_files = ""
if key_files:
prompt_files += f"Web Information Source(s) As Follows::\n"
for i, file_info in enumerate(key_files, 1):
if file_info.get('file_path') in key_files_dict:
file_info = key_files_dict[file_info.get('file_path')]
index = file_info.get('index')
# 通过file_path获取原始网页信息
file_path = file_info.get('file_path')
def get_file_head_content(file_path, max_length=10000):
try:
full_path = self._safe_join(file_path)
if not full_path.exists():
return f"[Error: File does not exist: {file_path}]"
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read(max_length)
return content
except Exception as e:
return f"[Error reading file {file_path}: {str(e)}]"
file_content = get_file_head_content(file_path)
doc_time = file_info.get('doc_time', 'Not specified')
source_authority = file_info.get('source_authority', 'Not specified')
task_relevance = file_info.get('task_relevance', 'Not specified')
# 开始组装这些字段的值
prompt_files += f"\n[webpaeg{index} begin]网页时间: {doc_time}|||网页权威性:{source_authority}|||网页相关性:{task_relevance}|||网页内容:{file_content}[webpaeg{index} end]"
# 设计system prompt
system_prompt = """You are a writing master. Next, you will receive web page information, user questions, and the structure of the current chapter. You need to integrate the user's questions with the provided web content and write the chapter based on its given structure. Additionally, an overall outline and summaries of previously completed chapters will be provided for reference to avoid repetition or contradictions and ensure logical consistency within the broader framework. Specific requirements will be detailed below.
When drafting the current chapter content, strictly comply with the following requirements:
- In the web page information I gave you, each result is in the format of [webpage X begin]...[webpage X end], where X represents the numerical index of each article. Please cite the context at the end of the sentence when appropriate. Please cite the context in the corresponding part of the answer in the format of the reference number [citation:X]. If a sentence comes from multiple contexts, please list all relevant reference numbers, such as [citation:3][citation:5]. Remember not to collect the references at the end and return the reference numbers, but list them in the corresponding part of the answer.
- You can only use the provided web page information for writing, don't make up any content, ensure the accuracy of the facts. Note that when there are contradictions between the facts described in the above search results, you should use your internal knowledge to reasonably identify the correct information. If identification is impossible, you may select the most factual result based on the authority of the web pages and a voting mechanism (e.g., the description consistent with the majority of web pages). If judgment remains impossible using these methods, you may appropriately list possible differing statements, but you must not conflate different claims—prioritize ensuring factual accuracy!
- You are only permitted to write content strictly within the provided chapter framework. You are forbidden from creating additional subheadings or bullet points within the framework! However, there is a special exception: You may appropriately use tables for narration when necessary. Furthermore, you are not allowed to use concise or summarizing language for narration! We must strictly ensure the information density of the writing and avoid excessive compression.
- You cannot make any changes to the structure of the chapter you are currently writing, such as the title content and the bold symbols in the title, you are not allowed to make any changes. **Important Note:** When writing Chapter 1, if you find the chapter lacks article title, you must create one based on user query. However, this rule only applies to Chapter 1 - do not add any titles to any other chapters in the work.
- Be careful to ensure that the narrative content is highly relevant and does not contain any common sense errors, note that although you are asked to ensure the richness of information when writing, you must ensure that the content you write is highly relevant and that the context is logically coherent and readable.
- Proceeding to explain the roles of other specified fields:
* user_query: The user query, ensure the drafted content is highly relevant to the user's inquiry.
* written_chapters: Reference written_chapters to avoid large amounts of repetitive or conflicting content
* overall_outline: The purpose of giving an overall outline is to let you understand the summary of the article and avoid content inconsistent with other parts during your writing. In short, focus on writing the current chapter.
* task_content: The task_content may provide the requirements for writing the current chapter as well as prompts for what to avoid. You can refer to this content when drafting.
Other points to note::
- If the first chapter is an **Abstract** or **Introduction**, do not include subheadings (level-2 or finer bullet points)—begin the content directly under the level-1 heading.
- CONTENT LENGTH: Each section should contain approximately 2500 words to ensure comprehensive coverage.
- **CRITICAL TITLE PRESERVATION RULE:** You MUST preserve the exact format, structure, and content of chapter titles as provided in the current_chapter_outline. This includes:
* DO NOT change any markdown formatting symbols (# ## ### ** etc.)
* DO NOT add, remove, or rearrange any part of the title structure
* Copy the title lines EXACTLY as they appear in current_chapter_outline
* Only write content under the provided title structure - never modify the titles themselves
* When the title symbols in the current chapter outline are inconsistent with those in the overall outline, use the overall outline's title symbols as the standard and maintain symbol consistency throughout the writing process
- Note that in Chapter 1, omit any mention of research objectives, methodology, or procedural details.
- Be sure to ensure that the language of your output is consistent with the language of the user's question. For example, if the user's question is in Chinese, your reply should also be in Chinese.
Strictly follow the following format for output:
<chapter_content>xxx</chapter_content>
"""
user_prompt = f"""TASK CONTENT: {task_content}
WEB PAGE INFORMATION: {prompt_files}
OVERALL OUTLINE: {overall_outline}
CURRENT CHAPTER OUTLINE: {current_chapter_outline}
PREVIOUSLY WRITTEN CHAPTERS SUMMARY: {written_chapters_summary}
USER QUERY: {user_query}"""
# 调用AI模型进行分类
# Get model URL and token from config
config = get_config()
model_config = config.get_custom_llm_config()
model_url = model_config.get('url') or os.getenv('MODEL_REQUEST_URL', '')
model_token = model_config.get('token') or os.getenv('MODEL_REQUEST_TOKEN', '')
headers = {'Content-Type': 'application/json', 'csb-token': model_token}
try:
max_retries = 5
response = None
for attempt in range(max_retries):
try:
response = requests.post(
url=model_url,
headers=headers,
json={
"model": model_config.get('model', 'pangu_auto'),
"chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<s>[unused9]系统:[unused10]' }}{% endif %}{% if message['role'] == 'system' %}{{'<s>[unused9]系统:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'assistant' %}{{'[unused9]助手:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'tool' %}{{'[unused9]工具:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'function' %}{{'[unused9]方法:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'user' %}{{'[unused9]用户:' + message['content'] + '[unused10]'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[unused9]助手:' }}{% endif %}",
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"}
],
"spaces_between_special_tokens": False,
"max_tokens": max_tokens,
"temperature": temperature,
},
timeout=model_config.get("timeout", 180)
)
response = response.json()
logger.debug(f"API response received")
break # Success, exit retry loop
except Exception as e:
logger.warning(f"LLM API call attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
raise e # Last attempt, re-raise the exception
time.sleep(5) # Simple 1 second delay between retries
if response is None:
raise Exception("Failed to get response after all retries")
# ai_response = response.choices[0].message.content.strip()
ai_response = response["choices"][0]["message"]["content"].strip()
# Extract content from first response
content = ""
if "<chapter_content>" in ai_response:
content = ai_response.split("<chapter_content>")[1].split("</chapter_content>")[0].strip()
else:
content = ai_response
logger.debug(f"Content before correction: {content[:200]}...")
logger.debug(f"Overall outline: {overall_outline[:200]}...")
content = self._correct_title_format(content, overall_outline)
logger.debug(f"Content after correction: {content[:200]}...")
# Second round: Request summary
summary_prompt = "Please give a brief summary of the output chapter content. Be sure to ensure that the language of the summary is consistent with the language of the output chapter content. For example, if the chapter content is in Chinese, your summary should also be in Chinese."
summary_response = None
max_retries = 5
for attempt in range(max_retries):
try:
summary_response = requests.post(
url=model_url,
headers=headers,
json={
"model": model_config.get('model', 'pangu_auto'),
"chat_template":"{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<s>[unused9]系统:[unused10]' }}{% endif %}{% if message['role'] == 'system' %}{{'<s>[unused9]系统:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'assistant' %}{{'[unused9]助手:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'tool' %}{{'[unused9]工具:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'function' %}{{'[unused9]方法:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'user' %}{{'[unused9]用户:' + message['content'] + '[unused10]'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[unused9]助手:' }}{% endif %}",
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"},
{"role": "assistant", "content": ai_response},
{"role": "user", "content": summary_prompt + " /no_think"}
],
"max_tokens": max_tokens,
"spaces_between_special_tokens": False,
"temperature": temperature,
},
timeout=model_config.get("timeout", 180)
)
summary_response = summary_response.json()
logger.debug(f"Summary API response received")
break # Success, exit retry loop
except Exception as e:
logger.warning(f"Summary LLM API call attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
raise e # Last attempt, re-raise the exception
time.sleep(5) # Simple delay between retries
if summary_response is None:
raise Exception("Failed to get summary response after all retries")
# summary_ai_response = summary_response.choices[0].message.content.strip()
summary_ai_response = summary_response["choices"][0]["message"]["content"].strip()
summary = summary_ai_response
session_context = self.get_session_context()
session_id = session_context.get("session_id")
# Save multi-round conversation history
conversation_history = [
# {"role": "system", "content": "system 1"},
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"},
{"role": "assistant", "content": ai_response},
{"role": "user", "content": summary_prompt + " /no_think"},
{"role": "assistant", "content": summary_ai_response}
]
# 把当前内容写入到target_file_path中
write_result = self.file_write(file_path=target_file_path,
content=content,
create_dirs=True)
if not write_result.success:
raise Exception(f"File write failed: {write_result.error}")
results = []
return MCPToolResult(
success=True,
data=results.append({
"chapter_summary": summary,
}),
metadata={
'content_length': len(content),
'summary_length': len(summary)
}
)
except Exception as e:
logger.error(f"AI model call failed: {e}")
return MCPToolResult(
success=False,
error=f"section writer failed: {str(e)}"
)
except Exception as e:
logger.error(f"section writer failed: {e}")
return MCPToolResult(success=False, error=str(e))
def merge_reports(self, section_contents, output_file):
report_files = []
for section_content in section_contents:
# Handle both dict format (expected) and string format (fallback)
if isinstance(section_content, dict):
file_path = section_content.get('file_path')
else:
# Fallback for direct string paths
file_path = section_content
if file_path:
full_path = self._safe_join(file_path)
report_files.append(full_path)
# 提取文件名中的数字索引并排序
def extract_index(file_path):
"""从文件名中提取数字索引"""
filename = os.path.basename(file_path)
match = re.search(r'part_(\d+)\.md', filename)
if match:
return int(match.group(1))
return None # 不符合格式的文件
# 创建(索引, 文件路径)元组列表并排序
indexed_files = []
for file_path in report_files:
idx = extract_index(file_path)
if idx is not None:
indexed_files.append((idx, file_path))
# 按索引排序
indexed_files.sort(key=lambda x: x[0])
if not indexed_files:
logger.warning("No report_*.md files found matching criteria")
return
# 合并文件
try:
with open(output_file, 'w', encoding='utf-8') as outfile:
for idx, file_path in indexed_files:
filename = os.path.basename(file_path)
try:
with open(file_path, 'r', encoding='utf-8') as infile:
# 写入文件内容
outfile.write(infile.read())
outfile.write("\n\n")
# 添加分隔标记
# outfile.write(f"\n\n--- 文件结束: {filename} ---\n\n")
logger.info(f"Merged: {filename}")
except Exception as e:
logger.warning(f"Unable to read file {filename}: {str(e)}")
logger.info(f"\nMerge completed! The result is saved at: {output_file}")
logger.info(f"A total of {len(indexed_files)} files have been merged.")
except Exception as e:
logger.error(f"Error: Failed to write to output file - {str(e)}")
# 清理可能创建的不完整输出文件
if os.path.exists(output_file):
os.remove(output_file)
raise
def concat_section_files(
self,
section_files: List[Dict],
final_file_path: str
) -> MCPToolResult:
"""
Concatenate the content of the saved section files into a single file
"""
try:
logger.debug(f"Starting file concatenation: section_files={section_files}, final_file={final_file_path}")
# Convert relative path to absolute if needed
final_file_path = self._safe_join(final_file_path)
output_dir = os.path.dirname(final_file_path)
if output_dir:
os.makedirs(output_dir, exist_ok=True)
# 读取section_files中的文件内容
self.merge_reports(section_files, final_file_path)
return MCPToolResult(
success=True,
data={"merged_files": len(section_files), "output_path": str(final_file_path)},
metadata={
'final_file_path': str(final_file_path),
'section_count': len(section_files)
}
)
except Exception as e:
logger.error(f"Concatenate section files failed: {e}")
return MCPToolResult(success=False, error=str(e))
def document_extract(
self,
# save_analysis_file_path: str,
tasks: List[Dict],
model: str = "pangu_auto",
temperature: Optional[float] = None,
max_tokens: Optional[int] = None,
max_workers: int = 5
) -> MCPToolResult:
"""
Multi-dimensional analysis of locally stored files using AI models.
Evaluates each file across four key dimensions: source authority, core content extraction,
information richness, and query relevance scoring.
Args:
tasks: List of task dictionaries containing:
- file_path: Relative path to the file (relative to workspace root) to read
- task: task for relevance assessment
model: AI model to use for multi-dimensional analysis
temperature: Creativity level for the AI response (0-1)
max_tokens: Maximum tokens for the AI response
max_workers: Maximum number of concurrent model API requests
"""
try:
# Get configuration
from config.config import get_model_config, get_storage_config
model_config = get_model_config()
storage_config = get_storage_config()
# Use config values or defaults
if temperature is None:
temperature = model_config.get('temperature', 0.3)
if max_tokens is None:
max_tokens = model_config.get('max_tokens', 8192)
logger.debug(f"Starting document extraction: tasks={tasks}")
def process_single_task(task: Dict) -> Dict:
file_path = task['file_path']
task_content = task['task']
# 1. 读取文件内容
read_result = self.file_read(file_path)
if not read_result.success:
return {
'file_path': file_path,
'task': task_content,
'success': False,
'error': f"File read error: {read_result.error}",
'answer': None
}
content = read_result.data
system_prompt = (
"You are a text expert. Next, you will be given a document and task content. You need to analyze this document carefully and then provide multiple dimensional information for this document.\n\n"
"The following are some dimensional information extracted:\n"
"1. Web page time: According to the content of the document, extract the web page time of the document content. If it cannot be judged, it is expressed as \"unable to determine the web page time\"; otherwise, the time of the web page is output, accurate to the month, in the format of \"YYYY year MM month\", such as \"2023 June\";\n"
"2. Authority: According to the information of the document, judge the source of the web page to confirm the credibility of the web page.\n"
"3. Relevance: According to the current task (task_content) and the given document, judge whether the current document is related to the current task.\n"
"4. Core content: Based on this document, you make a core content summary to ensure the richness of information, with a word count of about 200 words.\n"
"Information richness: Estimate the total word count of substantive content in the document. Less than 200 words indicates scarcity; over 800 words suggests high richness; between these thresholds denotes moderate richness. Be careful not to just give the word count results, but also give a corresponding text description of how informative the content is.\n"
"Note:\n1. Ensure the document's language aligns with the extracted dimensions (e.g., Chinese content requires Chinese extraction).\n2. For **source_authority** and **task_relevance**, first provide a brief description before concluding. \n"
"- **Authority**: Briefly assess the source's credibility (e.g., expertise, reputation). *Conclusion*: [High/Medium/Low]. \n"
"- **Relevance**: Summarize content alignment with the topic. *Conclusion*: [High/Medium/Low].\n"
"The final output format must be a valid JSON object:\n"
"{\n"
" \"doc_time\": \"xxx\",\n"
" \"source_authority\": \"xxx\",\n"
" \"task_relevance\": \"xxx\",\n"
" \"core_content\": \"xxx\",\n"
" \"information_richness\": \"xxx\"\n"
"}\n\n"
"Important: Return ONLY the JSON object, no additional text or formatting."
)
# 构建用户提示
user_prompt = (
f"DOCUMENT CONTENT:\n{content}\n"
# f"DOCUMENT LEN: The length of the file content is{len(content)}\n"
f"TASK FOR RELEVANCE ASSESSMENT: {task_content}"
)
# Get model URL and token from config
config = get_config()
model_config = config.get_custom_llm_config()
model_url = model_config.get('url') or os.getenv('MODEL_REQUEST_URL', '')
model_token = model_config.get('token') or os.getenv('MODEL_REQUEST_TOKEN', '')
headers = {'Content-Type': 'application/json', 'csb-token': model_token}
try:
# Add retry logic for AI model call
max_retries = 5
response = None
for attempt in range(max_retries):
try:
response = requests.post(
url=model_url,
headers=headers,
json={
"model": model_config.get('model', 'pangu_auto'),
"chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<s>[unused9]系统:[unused10]' }}{% endif %}{% if message['role'] == 'system' %}{{'<s>[unused9]系统:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'assistant' %}{{'[unused9]助手:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'tool' %}{{'[unused9]工具:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'function' %}{{'[unused9]方法:' + message['content'] + '[unused10]'}}{% endif %}{% if message['role'] == 'user' %}{{'[unused9]用户:' + message['content'] + '[unused10]'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[unused9]助手:' }}{% endif %}",
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"}
],
"max_tokens": max_tokens,
"spaces_between_special_tokens": False,
"temperature": temperature,
},
timeout=model_config.get("timeout", 180)
)
response = response.json()
logger.info(f"LLM API response: {response}")
break # Success, exit retry loop
except Exception as e:
logger.warning(f"LLM API call attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
raise e # Last attempt, re-raise the exception
time.sleep(4) # Simple 1 second delay between retries
if response is None:
raise Exception("Failed to get response after all retries")
# answer = response.choices[0].message.content
answer = response["choices"][0]["message"]["content"]
session_context = self.get_session_context()
session_id = session_context.get("session_id")
# 切换保存的方式
conversation_history = [
# {"role": "system", "content": "system 1"},
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt + " /no_think"},
{"role": "assistant", "content": answer}
]
return {
'file_path': file_path,
'task': task_content,
'success': True,
'answer': answer,
'metadata': {
'file_size': len(content),
'line_count': len(content.splitlines())
}
}
except Exception as e:
logger.error(f"Model API call failed for file '{file_path}': {e}")
return {
'file_path': file_path,
'task': task_content,
'success': False,
'error': f"Model API error: {str(e)}"
}
# 4. 并发处理所有任务
results = []
with ThreadPoolExecutor(max_workers=min(max_workers, len(tasks))) as executor:
future_to_task = {executor.submit(process_single_task, task): task for task in tasks}
for future in as_completed(future_to_task):
try:
result = future.result()
results.append(result)
except Exception as e:
task = future_to_task[future]
logger.error(f"Task processing failed for file '{task['file_path']}': {e}")
results.append({
'file_path': task['file_path'],
'task': task['task'],
'success': False,
'error': f"Task processing exception: {str(e)}"
})
# 5. 保持原始任务顺序
task_order = {task['file_path']: i for i, task in enumerate(tasks)}
results.sort(key=lambda x: task_order.get(x['file_path'], float('inf')))
# 保存结果到文件
def parse_answer_to_structured_data(answer_text: str, file_path: str) -> Dict[str, str]:
"""Parse the AI JSON response into structured data"""
# Default structure
structured_data = {
"file_path": file_path,
"doc_time": "Unknown",
"source_authority": "Unknown",
"task_relevance": "Unknown",
"information_richness": "Unknown",
"core_content": "Unknown"
}
if not answer_text:
return structured_data
try:
# Try to parse as JSON
answer_text = answer_text.strip()
# Remove any markdown code blocks if present
if answer_text.startswith('```'):
lines = answer_text.split('\n')
# Find the start and end of JSON content
start_idx = 0
end_idx = len(lines)
for i, line in enumerate(lines):
if line.strip().startswith('{'):
start_idx = i
break
for i in range(len(lines) - 1, -1, -1):
if lines[i].strip().endswith('}'):
end_idx = i + 1
break
answer_text = '\n'.join(lines[start_idx:end_idx])
# Parse JSON
parsed_data = json.loads(answer_text)
# Update structured_data with parsed values
if isinstance(parsed_data, dict):
structured_data.update({
"file_path": file_path,
"doc_time": parsed_data.get("doc_time", "Unknown"),
"source_authority": parsed_data.get("source_authority", "Unknown"),
"task_relevance": parsed_data.get("task_relevance", "Unknown"),
"core_content": parsed_data.get("core_content", "Unknown"),
"information_richness": parsed_data.get("information_richness", "Unknown")
})
return structured_data
except json.JSONDecodeError as e:
# If JSON parsing fails, return default with error info
structured_data[
"core_content"] = f"JSON parsing error: {str(e)}. Raw response: {answer_text[:200]}..."
return structured_data
except Exception as e:
# Handle any other parsing errors
structured_data["core_content"] = f"Parsing error: {str(e)}"
return structured_data
# Transform results into the desired format
structured_results = []
for result in results:
if result.get('success', False) and result.get('answer'):
structured_data = parse_answer_to_structured_data(
result['answer'],
result['file_path']
)
structured_results.append(structured_data)
else:
# For failed results, still include basic info
structured_results.append({
"file_path": result.get('file_path', 'Unknown'),
"doc_time": "Processing failed",
"source_authority": "Processing failed",
"task_relevance": "Processing failed",
"information_richness": "Unknown",
"core_content": f"Error: {result.get('error', 'Unknown error')}"
})
# Save structured results to JSON file
# Create full path relative to workspace
analysis_path = storage_config.get('document_analysis_path', './doc_analysis')
full_save_path = self.workspace_path / analysis_path / "file_analysis.jsonl"
full_save_path.parent.mkdir(parents=True, exist_ok=True)
# with open(full_save_path, "a", encoding='utf-8') as f:
# json.dump(structured_results, f, ensure_ascii=False, indent=2)
with open(full_save_path, mode="a", encoding='utf-8') as f:
for ii in structured_results:
f.write(json.dumps(ii, ensure_ascii=False) + "\n")
# 6. 统计结果
successful_tasks = len([r for r in results if r.get('success', False)])
return MCPToolResult(
success=True,
data=results,
metadata={
'total_tasks': len(tasks),
'successful_tasks': successful_tasks,
'failed_tasks': len(tasks) - successful_tasks,
'model': model,
'concurrent_workers': min(max_workers, len(tasks))
}
)
except Exception as e:
logger.error(f"Context-based document extraction failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ FILE DOWNLOAD TOOLS ================
def download_files(
self,
urls: List[str],
target_directory: str = None,
overwrite: bool = False,
max_file_size_mb: int = 100
) -> MCPToolResult:
"""
Download human-readable research files such as PDFs, documents, and data files.
Use this tool for downloading research papers, documentation, reports, data files (CSV, JSON, XML),
academic publications, and other human-readable content that you can analyze.
WARNING: Do NOT use this tool for downloading web pages (HTML/HTM files) or other non-readable formats.
For web page content extraction, use the url_crawler tool instead.
Args:
urls: List of URLs to download (PDFs, DOCs, research papers, data files, etc.)
target_directory: Directory to save files (relative to session workspace)
overwrite: Whether to overwrite existing files
max_file_size_mb: Maximum file size in MB
"""
try:
if target_directory:
# Ensure target_directory is relative to session workspace for security
download_dir = self._safe_join(target_directory)
else:
download_dir = self.workspace_path / "downloads"
download_dir.mkdir(parents=True, exist_ok=True)
def download_single_file(url: str) -> Dict[str, Any]:
"""Download a single file"""
try:
# Parse URL to get filename
parsed_url = urlparse(url)
filename = os.path.basename(parsed_url.path) or 'downloaded_file'
# Ensure filename has extension
if '.' not in filename:
filename += '.html' # Default extension
if os.path.isabs(filename):
raise Exception(f"Path '{filename}' is absolute. Only relative paths are allowed.")
file_path = download_dir / filename
if not os.path.realpath(file_path).startswith(self.full_workspace_path):
raise Exception(f"Path '{filename}' is outside workspace directory.")
# Check if file exists
if file_path.exists() and not overwrite:
return {
'url': url,
'success': False,
'error': 'File already exists',
'file_path': str(file_path)
}
# Download file
response = requests.get(url, stream=True, timeout=30)
response.raise_for_status()
# Check file size
content_length = response.headers.get('content-length')
if content_length and int(content_length) > max_file_size_mb * 1024 * 1024:
return {
'url': url,
'success': False,
'error': f'File too large (>{max_file_size_mb}MB)',
'file_path': None
}
# Save file
with open(file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return {
'url': url,
'success': True,
'file_path': str(file_path),
'file_size': file_path.stat().st_size
}
except Exception as e:
return {
'url': url,
'success': False,
'error': str(e),
'file_path': None
}
# Process downloads concurrently
results = []
max_concurrent_downloads = min(5, len(urls)) # Limit concurrent downloads to avoid overwhelming servers
with ThreadPoolExecutor(max_workers=max_concurrent_downloads) as executor:
# Submit all download tasks
future_to_url = {executor.submit(download_single_file, url): url for url in urls}
# Collect results as they complete
for future in as_completed(future_to_url):
try:
result = future.result()
results.append(result)
except Exception as e:
url = future_to_url[future]
logger.error(f"Download task failed for '{url}': {e}")
results.append({
'url': url,
'success': False,
'error': f"Download task exception: {str(e)}",
'file_path': None
})
# Sort results to maintain original URL order
url_order = {urls[i]: i for i in range(len(urls))}
results.sort(key=lambda x: url_order.get(x['url'], float('inf')))
# Generate status message following context management philosophy
successful_downloads = len([r for r in results if r.get('success', False)])
failed_downloads = len(results) - successful_downloads
status_msg = f"File download task completed. Processed {len(urls)} URLs with {successful_downloads} successful downloads and {failed_downloads} failures. Files saved to {download_dir.relative_to(self.workspace_path)}. Use file reading tools to examine the downloaded files."
return MCPToolResult(
success=True,
data=status_msg,
metadata={
'download_directory': str(download_dir),
'total_urls': len(urls),
'successful_downloads': successful_downloads,
'failed_downloads': failed_downloads
}
)
except Exception as e:
logger.error(f"Download files failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ WORKSPACE TOOLS ================
def list_workspace(
self,
path: str = None,
recursive: bool = False,
include_hidden: bool = False,
max_depth: int = 3
) -> MCPToolResult:
"""
List files and directories in workspace with tree structure visualization
Args:
path: Specific path to list (relative to session workspace)
recursive: Whether to list recursively
include_hidden: Whether to include hidden files
max_depth: Maximum recursion depth
"""
try:
if path:
# Ensure path is relative to session workspace for security
target_path = self._safe_join(path)
else:
target_path = self.workspace_path
if not target_path.exists():
return MCPToolResult(
success=False,
error=f"Path does not exist: {target_path}"
)
if not target_path.is_dir():
return MCPToolResult(
success=False,
error=f"Path is not a directory: {target_path}"
)
items = []
tree_structure = []
def _list_items(current_path: Path, current_depth: int = 0):
if current_depth > max_depth:
return
try:
# Get all items and sort them (directories first, then files, both alphabetically)
all_items = list(current_path.iterdir())
if not include_hidden:
all_items = [item for item in all_items if not item.name.startswith('.')]
# Sort: directories first, then files, both alphabetically
all_items.sort(key=lambda x: (not x.is_dir(), x.name.lower()))
for item in all_items:
item_info = {
'name': item.name,
'path': str(item.relative_to(self.workspace_path)),
'type': 'directory' if item.is_dir() else 'file',
'size': item.stat().st_size if item.is_file() else None,
'modified': item.stat().st_mtime,
'depth': current_depth
}
items.append(item_info)
# Recurse into directories
if recursive and item.is_dir():
_list_items(item, current_depth + 1)
except PermissionError:
pass # Skip directories we can't read
def _generate_tree_structure(current_path: Path, prefix: str = "", is_last: bool = True,
current_depth: int = 0):
"""Generate ASCII tree structure recursively"""
if current_depth > max_depth:
return
try:
# Get all items and sort them (directories first, then files, both alphabetically)
all_items = list(current_path.iterdir())
if not include_hidden:
all_items = [item for item in all_items if not item.name.startswith('.')]
# Sort: directories first, then files, both alphabetically
all_items.sort(key=lambda x: (not x.is_dir(), x.name.lower()))
for i, item in enumerate(all_items):
is_last_item = i == len(all_items) - 1
# Choose the appropriate tree symbols
if is_last_item:
current_symbol = "└── "
extension = " "
else:
current_symbol = "├── "
extension = "│ "
# Add file/directory indicator
if item.is_dir():
name_with_indicator = f"📁 {item.name}/"
else:
# Add file size for files
try:
size = item.stat().st_size
if size < 1024:
size_str = f"{size}B"
elif size < 1024 * 1024:
size_str = f"{size / 1024:.1f}KB"
else:
size_str = f"{size / (1024 * 1024):.1f}MB"
name_with_indicator = f"📄 {item.name} ({size_str})"
except:
name_with_indicator = f"📄 {item.name}"
tree_line = prefix + current_symbol + name_with_indicator
tree_structure.append(tree_line)
# Recurse into directories
if recursive and item.is_dir():
_generate_tree_structure(
item,
prefix + extension,
is_last_item,
current_depth + 1
)
except PermissionError:
tree_structure.append(prefix + "└── [Permission Denied]")
# Generate both flat list and tree structure
_list_items(target_path)
# Generate tree structure
root_name = target_path.name if target_path.name else "workspace"
tree_structure.append(f"📁 {root_name}/")
if recursive:
_generate_tree_structure(target_path)
else:
# For non-recursive, just show immediate children
try:
all_items = list(target_path.iterdir())
if not include_hidden:
all_items = [item for item in all_items if not item.name.startswith('.')]
all_items.sort(key=lambda x: (not x.is_dir(), x.name.lower()))
for i, item in enumerate(all_items):
is_last_item = i == len(all_items) - 1
symbol = "└── " if is_last_item else "├── "
if item.is_dir():
name_with_indicator = f"📁 {item.name}/"
else:
try:
size = item.stat().st_size
if size < 1024:
size_str = f"{size}B"
elif size < 1024 * 1024:
size_str = f"{size / 1024:.1f}KB"
else:
size_str = f"{size / (1024 * 1024):.1f}MB"
name_with_indicator = f"📄 {item.name} ({size_str})"
except:
name_with_indicator = f"📄 {item.name}"
tree_structure.append(symbol + name_with_indicator)
except PermissionError:
tree_structure.append("└── [Permission Denied]")
# Create the tree string
tree_string = "\n".join(tree_structure)
return MCPToolResult(
success=True,
data={
'items': items,
'tree_structure': tree_string,
'tree_lines': tree_structure
},
metadata={
'target_path': str(target_path.relative_to(self.workspace_path)) if path else '.',
'total_items': len(items),
'recursive': recursive,
'max_depth': max_depth,
'include_hidden': include_hidden
}
)
except Exception as e:
logger.error(f"List workspace failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ FILE EDITING TOOLS ================
def str_replace_based_edit_tool(
self,
action: str,
file_path: str,
content: str = None,
old_str: str = None,
new_str: str = None,
line_number: int = None,
max_char_len: int = 10000,
) -> MCPToolResult:
"""
Comprehensive file editing tool
Args:
action: 'create', 'view', 'str_replace', 'insert', 'append', 'delete'
file_path: Path to the file
content: Content for create action
old_str: String to replace (for str_replace)
new_str: Replacement string (for str_replace)
line_number: Line number for insert action
"""
try:
full_path = self._safe_join(file_path)
if action == 'create':
if full_path.exists():
return MCPToolResult(
success=False,
error=f"File already exists: {file_path}"
)
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(content or '', encoding='utf-8')
return MCPToolResult(
success=True,
data=f"File created: {file_path}",
metadata={'file_size': full_path.stat().st_size}
)
elif action == 'view':
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
content = full_path.read_text(encoding='utf-8')
if len(content) > max_char_len:
content = ("Due to the content being too long, only the first 10,000 characters are returned. "
"It is recommended to use other tools such as `document_qa` to extract the required content from the file. "
"Below is the returned portion of the file content: \n\n") + content[:max_char_len]
return MCPToolResult(
success=True,
data=content,
metadata={
'file_size': len(content),
'line_count': len(content.splitlines())
}
)
elif action == 'str_replace':
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
if not old_str or new_str is None:
return MCPToolResult(
success=False,
error="Both old_str and new_str are required for str_replace"
)
original_content = full_path.read_text(encoding='utf-8')
if old_str not in original_content:
return MCPToolResult(
success=False,
error=f"String not found: {old_str[:50]}..."
)
new_content = original_content.replace(old_str, new_str)
full_path.write_text(new_content, encoding='utf-8')
return MCPToolResult(
success=True,
data=f"Replaced {original_content.count(old_str)} occurrence(s)",
metadata={
'old_size': len(original_content),
'new_size': len(new_content)
}
)
elif action == 'insert':
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
if line_number is None or content is None:
return MCPToolResult(
success=False,
error="Both line_number and content are required for insert"
)
lines = full_path.read_text(encoding='utf-8').splitlines()
if line_number < 0 or line_number > len(lines):
return MCPToolResult(
success=False,
error=f"Invalid line number: {line_number}"
)
lines.insert(line_number, content)
full_path.write_text('\n'.join(lines), encoding='utf-8')
return MCPToolResult(
success=True,
data=f"Inserted content at line {line_number}",
metadata={'new_line_count': len(lines)}
)
elif action == 'append':
if not full_path.exists():
full_path.touch()
with open(full_path, 'a', encoding='utf-8') as f:
f.write(content or '')
return MCPToolResult(
success=True,
data=f"Appended content to {file_path}",
metadata={'file_size': full_path.stat().st_size}
)
elif action == 'delete':
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
full_path.unlink()
return MCPToolResult(
success=True,
data=f"Deleted file: {file_path}"
)
else:
return MCPToolResult(
success=False,
error=f"Unknown action: {action}"
)
except Exception as e:
logger.error(f"File edit failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ BASIC FILE TOOLS ================
def file_read(self, file_path: str, encoding: str = 'utf-8', max_char_len: int = 10000) -> MCPToolResult:
"""Read file content"""
try:
full_path = self._safe_join(file_path)
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
content = full_path.read_text(encoding=encoding)
if len(content) > max_char_len:
content = "Due to the content being too long, only the first 10,000 characters are returned. It is recommended to use other tools such as `document_qa` to extract the required content from the file. Below is the returned portion of the file content: \n\n" + content[:max_char_len]
return MCPToolResult(
success=True,
data=content,
metadata={
'file_size': len(content),
'line_count': len(content.splitlines()),
'encoding': encoding
}
)
except Exception as e:
logger.error(f"File read failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ ENHANCED FILE ANALYSIS TOOLS ================
def file_stats(self, file_path: str) -> MCPToolResult:
"""
Get comprehensive file statistics without reading full content.
Perfect for deciding whether to read full file or use targeted extraction.
Args:
file_path: Path to the file (relative to workspace)
"""
try:
full_path = self._safe_join(file_path)
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
if not full_path.is_file():
return MCPToolResult(
success=False,
error=f"Path is not a file: {file_path}"
)
# Get basic file stats
stat_info = full_path.stat()
file_size = stat_info.st_size
# Quick content analysis without loading full file
encoding = 'utf-8'
line_count = 0
word_count = 0
char_count = 0
first_lines = []
last_lines = []
try:
with open(full_path, 'r', encoding=encoding, errors='ignore') as f:
# Read first few lines for preview
for i, line in enumerate(f):
line_count += 1
if i < 5: # First 5 lines
first_lines.append(line.rstrip())
char_count += len(line)
word_count += len(line.split())
# For efficiency, stop detailed counting after reasonable limit
if line_count > 10000:
# Estimate remaining based on average
remaining_size = file_size - f.tell()
if remaining_size > 0:
avg_line_size = f.tell() / line_count
estimated_remaining_lines = int(remaining_size / avg_line_size)
line_count += estimated_remaining_lines
# Estimate words and chars
avg_chars_per_line = char_count / min(line_count, 10000)
avg_words_per_line = word_count / min(line_count, 10000)
char_count += int(remaining_size)
word_count += int(estimated_remaining_lines * avg_words_per_line)
break
# Get last few lines if file is reasonable size
if file_size < 1024 * 1024: # Less than 1MB
with open(full_path, 'r', encoding=encoding, errors='ignore') as f:
lines = f.readlines()
last_lines = [line.rstrip() for line in lines[-5:]]
if line_count <= 10000: # Recalculate if we estimated
line_count = len(lines)
char_count = sum(len(line) for line in lines)
word_count = sum(len(line.split()) for line in lines)
except Exception as e:
# Try binary mode to at least get size info
encoding = 'binary'
char_count = file_size
# Determine file type
file_extension = full_path.suffix.lower()
file_type = self._detect_file_type(full_path, file_extension)
# Reading recommendation
reading_recommendation = self._get_reading_recommendation(
file_size, line_count, word_count, file_type
)
stats = {
'file_path': file_path,
'file_size_bytes': file_size,
'file_size_human': self._format_file_size(file_size),
'line_count': line_count,
'word_count': word_count,
'character_count': char_count,
'encoding': encoding,
'file_type': file_type,
'file_extension': file_extension,
'modified_time': stat_info.st_mtime,
'is_large_file': file_size > 1024 * 1024, # > 1MB
'is_very_large_file': file_size > 10 * 1024 * 1024, # > 10MB
'first_lines_preview': first_lines,
'last_lines_preview': last_lines,
'reading_recommendation': reading_recommendation
}
return MCPToolResult(
success=True,
data=stats,
metadata={
'analysis_method': 'efficient_sampling' if line_count > 10000 else 'full_analysis'
}
)
except Exception as e:
logger.error(f"File stats failed: {e}")
return MCPToolResult(success=False, error=str(e))
@staticmethod
def _detect_file_type(file_path: Path, extension: str) -> str:
"""Detect file type based on extension and content"""
# Extension-based detection
type_map = {
'.py': 'python_code',
'.js': 'javascript_code',
'.ts': 'typescript_code',
'.java': 'java_code',
'.cpp': 'cpp_code',
'.c': 'c_code',
'.html': 'html_markup',
'.css': 'css_stylesheet',
'.json': 'json_data',
'.xml': 'xml_data',
'.yaml': 'yaml_config',
'.yml': 'yaml_config',
'.md': 'markdown_document',
'.txt': 'plain_text',
'.csv': 'csv_data',
'.sql': 'sql_code',
'.sh': 'shell_script',
'.dockerfile': 'docker_config',
'.env': 'environment_config'
}
if extension in type_map:
return type_map[extension]
# Content-based detection for unknown extensions
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
first_line = f.readline().strip()
if first_line.startswith('#!'):
return 'executable_script'
elif first_line.startswith('<?xml'):
return 'xml_data'
elif first_line.startswith('{') or first_line.startswith('['):
return 'json_data'
elif 'DOCTYPE html' in first_line or '<html' in first_line:
return 'html_markup'
except:
pass
return 'unknown_text'
def _format_file_size(self, size_bytes: int) -> str:
"""Format file size in human readable format"""
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
return f"{size_bytes / 1024:.1f} KB"
elif size_bytes < 1024 * 1024 * 1024:
return f"{size_bytes / (1024 * 1024):.1f} MB"
else:
return f"{size_bytes / (1024 * 1024 * 1024):.1f} GB"
def _get_reading_recommendation(self, file_size: int, line_count: int,
word_count: int, file_type: str) -> Dict[str, Any]:
"""Provide intelligent recommendations for how to read the file"""
recommendations = {
'strategy': 'full_read',
'reason': 'File is small enough for full reading',
'alternatives': []
}
# Large file strategies
if file_size > 1024 * 1024: # > 1MB
recommendations['strategy'] = 'selective_read'
recommendations['reason'] = 'File is large, consider targeted approaches'
recommendations['alternatives'] = [
'Use file_grep_with_context to search for specific content',
'Use content_preview to get overview before full read',
'Use file_read_lines to read specific sections',
'Content indexing has been disabled'
]
elif line_count > 1000:
recommendations['strategy'] = 'preview_first'
recommendations['reason'] = 'Many lines, preview recommended before full read'
recommendations['alternatives'] = [
'Use content_preview for quick overview',
'Use file_grep_with_context for specific searches'
]
# File type specific recommendations
if file_type in ['json_data', 'xml_data']:
recommendations['alternatives'].append('Consider parsing structure instead of full text read')
elif file_type.endswith('_code'):
recommendations['alternatives'].append('Use grep to find specific functions/classes')
elif file_type == 'csv_data':
recommendations['alternatives'].append('Consider reading headers first with file_read_lines')
return recommendations
# ================ BASIC FILE TOOLS ================
def file_write(
self,
file_path: str,
content: str,
encoding: str = 'utf-8',
create_dirs: bool = True
) -> MCPToolResult:
"""Write content to file"""
try:
full_path = self._safe_join(file_path)
if create_dirs:
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(content, encoding=encoding)
return MCPToolResult(
success=True,
data=f"Written {len(content)} characters to {file_path}",
metadata={
'file_size': full_path.stat().st_size,
'encoding': encoding
}
)
except Exception as e:
logger.error(f"File write failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ SEARCH TOOLS ================
def file_find_by_name(
self,
name_pattern: str,
recursive: bool = True,
case_sensitive: bool = False,
max_results: int = 100
) -> MCPToolResult:
"""Find files by name pattern"""
try:
import fnmatch
if not case_sensitive:
name_pattern = name_pattern.lower()
matches = []
search_path = self.workspace_path
def _match_name(file_path: Path) -> bool:
name = file_path.name
if not case_sensitive:
name = name.lower()
return fnmatch.fnmatch(name, name_pattern)
# Search files
if recursive:
for file_path in search_path.rglob("*"):
if _match_name(file_path):
matches.append({
'name': file_path.name,
'path': str(file_path.relative_to(self.workspace_path)),
'type': 'directory' if file_path.is_dir() else 'file',
'size': file_path.stat().st_size if file_path.is_file() else None
})
if len(matches) >= max_results:
break
else:
for file_path in search_path.iterdir():
if _match_name(file_path):
matches.append({
'name': file_path.name,
'path': str(file_path.relative_to(self.workspace_path)),
'type': 'directory' if file_path.is_dir() else 'file',
'size': file_path.stat().st_size if file_path.is_file() else None
})
if len(matches) >= max_results:
break
return MCPToolResult(
success=True,
data=matches,
metadata={
'pattern': name_pattern,
'total_matches': len(matches),
'truncated': len(matches) >= max_results
}
)
except Exception as e:
logger.error(f"File find failed: {e}")
return MCPToolResult(success=False, error=str(e))
def file_read_lines(
self,
file_path: str,
start_line: int = 1,
end_line: int = None,
max_lines: int = 1000
) -> MCPToolResult:
"""
Read specific line ranges from a file without loading the entire file.
Perfect for reading specific sections after grep or for large files.
Args:
file_path: Path to the file
start_line: Starting line number (1-based)
end_line: Ending line number (1-based, None for end of file)
max_lines: Maximum number of lines to read (safety limit)
"""
try:
full_path = self._safe_join(file_path)
if not full_path.exists():
return MCPToolResult(
success=False,
error=f"File does not exist: {file_path}"
)
if start_line < 1:
return MCPToolResult(
success=False,
error="start_line must be >= 1"
)
lines_read = []
current_line = 0
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
current_line += 1
# Skip lines before start_line
if current_line < start_line:
continue
# Stop if we've reached end_line
if end_line and current_line > end_line:
break
# Safety check for max_lines
if len(lines_read) >= max_lines:
break
lines_read.append({
'line_number': current_line,
'content': line.rstrip('\n\r')
})
# Calculate actual end line
actual_end_line = lines_read[-1]['line_number'] if lines_read else start_line - 1
return MCPToolResult(
success=True,
data={
'file_path': file_path,
'start_line': start_line,
'end_line': actual_end_line,
'lines': lines_read,
'line_count': len(lines_read)
},
metadata={
'total_lines_read': len(lines_read),
'truncated_due_to_max_lines': len(lines_read) >= max_lines
}
)
except Exception as e:
logger.error(f"File read lines failed: {e}")
return MCPToolResult(success=False, error=str(e))
# ================ MCP TOOL SCHEMAS ================
MCP_TOOL_SCHEMAS = {
"think": {
"name": "think",
"description": "Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.",
"inputSchema": {
"type": "object",
"properties": {
"thought": {
"type": "string",
"description": "Your thoughts."
}
},
"required": ["thought"]
}
},
"reflect": {
"name": "reflect",
"description": "When multiple attempts yield no progress, use this tool to reflect on previous reasoning and planning, considering possible overlooked clues and exploring more possibilities. It will not obtain new information or make any changes to the repository.",
"inputSchema": {
"type": "object",
"properties": {
"reflect": {
"type": "string",
"description": "The specific content of your reflection"
}
},
"required": ["reflect"]
}
},
"batch_web_search": {
"name": "batch_web_search",
"description": "Search multiple queries using configurable search API with concurrent processing (no more than 8 search queries)",
"inputSchema": {
"type": "object",
"properties": {
"queries": {
"type": "array",
"items": {"type": "string"},
"description": "List of search queries"
},
"max_results_per_query": {
"type": "integer",
"default": 4,
"description": "Maximum search results per query (limited to 10)"
},
"max_workers": {
"type": "integer",
"default": 5,
"description": "Maximum number of concurrent search requests"
}
},
"required": ["queries"]
}
},
"url_crawler": {
"name": "url_crawler",
"description": "Extract content from web pages using configurable URL crawler API. Input is a list of documents with metadata including URL and local file path for saving extracted content.",
"inputSchema": {
"type": "object",
"properties": {
"documents": {
"type": "array",
"items": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "Web page URL to extract content from"
},
"file_path": {
"type": "string",
"description": "Local path to save extracted full text content"
},
"title": {
"type": "string",
"description": "Title of the web page"
},
"time": {
"type": "string",
"description": "Publication time of the web page"
}
},
"required": ["url", "file_path"]
},
"description": "List of documents with metadata including URL and save path"
},
"max_tokens_per_url": {
"type": "integer",
"default": 4000,
"description": "Maximum tokens per URL result"
},
"include_metadata": {
"type": "boolean",
"default": True,
"description": "Whether to include extraction metadata"
},
"max_workers": {
"type": "integer",
"default": 10,
"description": "Maximum number of concurrent extraction requests"
}
},
"required": ["documents"]
}
},
"document_qa": {
"name": "document_qa",
"description": "Answer questions based on content stored in local files. Each file has a corresponding question. Reads files and uses an AI model to answer each question using the respective file content as context.",
"inputSchema": {
"type": "object",
"properties": {
"tasks": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file (relative to workspace root)"
},
"question": {
"type": "string",
"description": "Question to ask about this file"
}
},
"required": ["file_path", "question"]
},
"description": "List of tasks, each containing a file path and a question"
},
"max_tokens": {
"type": "integer",
"default": 2000,
"description": "Maximum tokens for the AI response"
},
"max_workers": {
"type": "integer",
"default": 5,
"description": "Maximum number of concurrent model API requests"
}
},
"required": ["tasks"]
}
},
"download_files": {
"name": "download_files",
"description": "Download files from URLs to the workspace",
"inputSchema": {
"type": "object",
"properties": {
"urls": {
"type": "array",
"items": {"type": "string"},
"description": "List of URLs to download"
},
"target_directory": {
"type": "string",
"description": "Directory to save files"
},
"overwrite": {
"type": "boolean",
"default": False,
"description": "Whether to overwrite existing files"
},
"max_file_size_mb": {
"type": "integer",
"default": 100,
"description": "Maximum file size in MB"
}
},
"required": ["urls"]
}
},
"list_workspace": {
"name": "list_workspace",
"description": "List files and directories in the workspace",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Specify the directory path to list, using a relative path"
},
"recursive": {
"type": "boolean",
"default": False,
"description": "Whether to list recursively"
},
"include_hidden": {
"type": "boolean",
"default": False,
"description": "Whether to include hidden files"
},
"max_depth": {
"type": "integer",
"default": 3,
"description": "Maximum recursion depth"
}
},
"required": []
}
},
"str_replace_based_edit_tool": {
"name": "str_replace_based_edit_tool",
"description": "Create, view, and edit files with various operations",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["create", "view", "str_replace", "insert", "append", "delete"],
"description": "Action to perform"
},
"file_path": {
"type": "string",
"description": "Path to the file"
},
"content": {
"type": "string",
"description": "Content for create/insert/append actions"
},
"old_str": {
"type": "string",
"description": "String to replace (for str_replace)"
},
"new_str": {
"type": "string",
"description": "Replacement string (for str_replace)"
},
"line_number": {
"type": "integer",
"description": "Line number for insert action"
}
},
"required": ["action", "file_path"]
}
},
"file_read": {
"name": "file_read",
"description": "Read file content",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file (relative to workspace root)"
},
"encoding": {
"type": "string",
"default": "utf-8",
"description": "File encoding"
}
},
"required": ["file_path"]
}
},
"load_json": {
"name": "load_json",
"description": "Read json format file",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file (relative to workspace root)"
},
"encoding": {
"type": "string",
"default": "utf-8",
"description": "File encoding"
}
},
"required": ["file_path"]
}
},
"file_write": {
"name": "file_write",
"description": "Write content to file",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file (relative to workspace root)"
},
"content": {
"type": "string",
"description": "Content to write"
},
"encoding": {
"type": "string",
"default": "utf-8",
"description": "File encoding"
},
"create_dirs": {
"type": "boolean",
"default": True,
"description": "Create parent directories"
}
},
"required": ["file_path", "content"]
}
},
"file_find_by_name": {
"name": "file_find_by_name",
"description": "Find files by name pattern",
"inputSchema": {
"type": "object",
"properties": {
"name_pattern": {
"type": "string",
"description": "Name pattern to search for"
},
"recursive": {
"type": "boolean",
"default": True,
"description": "Search recursively"
},
"case_sensitive": {
"type": "boolean",
"default": False,
"description": "Case sensitive search"
},
"max_results": {
"type": "integer",
"default": 100,
"description": "Maximum number of results"
}
},
"required": ["name_pattern"]
}
},
"concat_section_files": {
"name": "concat_section_files",
"description": "Concatenate the content of the saved section files into a single file",
"inputSchema": {
"type": "object",
"properties": {
"final_file_path": {
"type": "string",
"description": "The final file path to save the concatenated content, save the file in the workspace **under the relative path `./report/`**, and specify the final_file_path as `./report/final_report.md`"
},
"section_files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the saved section file"
}
},
"required": ["file_path"]
},
"description": "List of section files to concatenate"
}
},
"required": ["section_files", "final_file_path"]
}
},
"search_result_classifier": {
"name": "search_result_classifier",
"description": "Intelligently classify and organize search result files according to a structured outline for comprehensive long-form content generation. Analyzes files across fouer key dimensions (document time, source authority, core content, and task relevance) and assigns relevant files to appropriate outline sections. Files may be assigned to multiple sections when their content spans different topics.",
"inputSchema": {
"type": "object",
"properties": {
"outline": {
"type": "string",
"description": "The outline here must be consistent with the content and structure of the outline generated above"
},
"key_files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file containing research content"
}
},
"required": ["file_path"]
},
"description": "List of research files to be classified according to the outline"
},
"model": {
"type": "string",
"default": "pangu_auto",
"description": "AI model to use for classification and organization"
},
"temperature": {
"type": "number",
"default": 0.3,
"description": "Creativity level for the AI classification (0-1)"
},
"max_tokens": {
"type": "integer",
"default": 2000,
"description": "Maximum tokens for the AI response"
}
},
"required": ["key_files", "outline"]
}
},
"document_extract": {
"name": "document_extract",
"description": "Multi-dimensional analysis of locally stored files using AI models. Evaluates each file across four key dimensions: web page time extraction, source authority assessment, task relevance evaluation, and core content summarization (~300 words). Provides structured document analysis for research and content evaluation purposes.",
"inputSchema": {
"type": "object",
"properties": {
"tasks": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file (relative to workspace root)"
},
"task": {
"type": "string",
"description": "The content of the currently executed subtask"
}
},
"required": ["file_path", "task"]
},
"description": "List of tasks, each containing a file path and the current task"
},
"model": {
"type": "string",
"default": "pangu_auto",
"description": "AI model to use for generating answers"
},
"temperature": {
"type": "number",
"default": 0.3,
"description": "Creativity level for the AI response (0-1)"
},
"max_tokens": {
"type": "integer",
"default": 2000,
"description": "Maximum tokens for the AI response"
},
"max_workers": {
"type": "integer",
"default": 5,
"description": "Maximum number of concurrent model API requests"
}
},
"required": ["tasks"]
}
},
"section_writer": {
"name": "section_writer",
"description": "Write the current chapter content based on given web information and chapter structure; also consider user questions, completed chapters, and overall outline to ensure content relevance while avoiding duplication or contradictions.",
"inputSchema": {
"type": "object",
"properties": {
"written_chapters_summary": {
"type": "string",
"description": "The summary of the written chapters, including the content of the chapters and the reflections on the chapters. Note that this field should be concatenated with the summaries of all previously written chapters with '\\n', and do not modify the original summary. For example, if the current chapter is the third chapter, the value of this field is 'chapter 1 summary \\n chapter 2 summary'. If not, the value is set to 'No previous chapters written yet.'"
},
"task_content": {
"type": "string",
"description": "Detailed description of some requirements for writing the current chapter and avoidance prompts. If there are reflections from the `think` tool on previously written chapters, they can be added to this field."
},
"user_query": {
"type": "string",
"description": "The user query, ensure the drafted content is highly relevant to the user's inquiry."
},
"current_chapter_outline": {
"type": "string",
"description": "This field represents the current chapter structure to be drafted. When composing the chapter content, do not modify content and bold formatting symbols of the existing structure's titles!!!"
},
"overall_outline": {
"type": "string",
"description": "This field represents the overall outline of the article. When drafting the chapter content, you should consider the overall outline to ensure the chapter content is consistent with the overall outline."
},
"target_file_path": {
"type": "string",
"description": "The path to save the chapter content"
},
"key_files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Relative path to the file containing research content"
}
},
"required": ["file_path"]
},
"description": "These files are the source materials required for drafting the current chapter."
},
"model": {
"type": "string",
"default": "pangu_auto",
"description": "AI model to use for classification and organization"
},
"temperature": {
"type": "number",
"default": 0.3,
"description": "Creativity level for the AI classification (0-1)"
},
"max_tokens": {
"type": "integer",
"default": 5000,
"description": "Maximum tokens for the AI response"
},
},
"required": ["user_query", "current_chapter_outline", "overall_outline", "target_file_path", "key_files"]
}
},
"file_stats": {
"name": "file_stats",
"description": "Get comprehensive file statistics without reading full content - perfect for deciding reading strategy",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the file (relative to workspace)"
}
},
"required": ["file_path"]
}
},
"file_read_lines": {
"name": "file_read_lines",
"description": "Read specific line ranges from a file without loading entire file - perfect for large files",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the file"
},
"start_line": {
"type": "integer",
"default": 1,
"description": "Starting line number (1-based)"
},
"end_line": {
"type": "integer",
"description": "Ending line number (1-based, None for end of file)"
},
"max_lines": {
"type": "integer",
"default": 1000,
"description": "Maximum number of lines to read (safety limit)"
}
},
"required": ["file_path"]
}
}
# NOTE: Task assignment tool schemas removed - these are now built-in methods of PlannerAgent
# to avoid circular dependency issues with sub-agents trying to create MCP client connections
}
# ================ MAIN INTERFACE ================
def get_tool_schemas() -> Dict[str, Any]:
"""Get all tool schemas for MCP registration"""
return MCP_TOOL_SCHEMAS
|