@devries-cameron20 / composio Mirror · read-only / commits / 9a1b0e99a
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 20:45 UTC

Feat: Experimental MCP and ToolRouter (#1985)

Co-authored-by: prateek <karnalprateek@gmail.com> Co-authored-by: Prateek <prateek@composio.dev>

Musthaq Ahamad committed Sep 26, 2025 at 19:18 UTC 9a1b0e99a78cce9bc9e4ba473241dc6b859f2057
79 files changed +3877 -1736
.changeset/huge-shoes-see.md deleted
-14
@@ -1,14 +0,0 @@
1 ----
2 -'@composio/core': patch
3 -'@composio/json-schema-to-zod': patch
4 -'@composio/anthropic': patch
5 -'@composio/cloudflare': patch
6 -'@composio/google': patch
7 -'@composio/langchain': patch
8 -'@composio/mastra': patch
9 -'@composio/openai': patch
10 -'@composio/openai-agents': patch
11 -'@composio/vercel': patch
12 ----
13 -
14 -Add support for experimental MCP
.changeset/pre.json deleted
-18
@@ -1,18 +0,0 @@
1 -{
2 - "mode": "pre",
3 - "tag": "rc",
4 - "initialVersions": {
5 - "composio-docs": "0.0.0",
6 - "@composio/core": "0.1.52",
7 - "@composio/json-schema-to-zod": "0.1.15",
8 - "@composio/anthropic": "0.1.52",
9 - "@composio/cloudflare": "0.1.52",
10 - "@composio/google": "0.1.52",
11 - "@composio/langchain": "0.1.52",
12 - "@composio/mastra": "0.1.53",
13 - "@composio/openai": "0.1.52",
14 - "@composio/openai-agents": "0.1.53",
15 - "@composio/vercel": "0.2.8"
16 - },
17 - "changesets": []
18 -}
.changeset/tricky-jars-wave.md new
+15
@@ -0,0 +1,15 @@
1 +---
2 +'@composio/core': patch
3 +'@composio/anthropic': patch
4 +'@composio/cloudflare': patch
5 +'@composio/google': patch
6 +'@composio/langchain': patch
7 +'@composio/mastra': patch
8 +'@composio/openai': patch
9 +'@composio/openai-agents': patch
10 +'@composio/vercel': patch
11 +---
12 +
13 +- Adds the new experiemntal ToolRouter, Deprecates the existing MCP experience and adds the new MCP components.
14 +- The old MCP components can be accessed via `deprecated.mcp` until the next release, where it will get removed.
15 +- Fixes `toolkits.list` and `toolkits.get` methods to add `description` to connection fields
pnpm-lock.yaml
+181 -246
@@ -13,10 +13,10 @@ catalogs:
13 specifier: ^4.20250917.0
14 version: 4.20250917.0
15 '@composio/client':
16 - specifier: 0.1.0-alpha.36
17 - version: 0.1.0-alpha.36
16 + specifier: 0.1.0-alpha.37
17 + version: 0.1.0-alpha.37
18 ai:
19 - specifier: ^5.0.44
19 + specifier: 5.0.44
20 version: 5.0.44
21 tsup:
22 specifier: ^8.5.0
@@ -158,7 +158,7 @@ importers:
158 version: 5.0.44(zod@3.25.76)
159 composio-core:
160 specifier: ^0.5.39
161 - version: 0.5.39(@ai-sdk/openai@2.0.16(zod@3.25.76))(@cloudflare/workers-types@4.20250917.0)(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@langchain/openai@0.5.13(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(ws@8.18.2))(ai@5.0.44(zod@3.25.76))(langchain@0.3.28(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@opentelemetry/api@1.9.0)(@opentelemetry/exporter-trace-otlp-proto@0.203.0(@opentelemetry/api@1.9.0))(@opentelemetry/sdk-trace-base@2.0.1(@opentelemetry/api@1.9.0))(axios@1.10.0)(openai@4.104.0(ws@8.18.2)(zod@3.25.76))(ws@8.18.2))(openai@4.104.0(ws@8.18.2)(zod@3.25.76))
161 + version: 0.5.39(@ai-sdk/openai@2.0.35(zod@3.25.76))(@cloudflare/workers-types@4.20250917.0)(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@langchain/openai@0.5.13(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(ws@8.18.2))(ai@5.0.44(zod@3.25.76))(langchain@0.3.28(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@opentelemetry/api@1.9.0)(@opentelemetry/exporter-trace-otlp-proto@0.203.0(@opentelemetry/api@1.9.0))(@opentelemetry/sdk-trace-base@2.0.1(@opentelemetry/api@1.9.0))(axios@1.10.0)(openai@4.104.0(ws@8.18.2)(zod@3.25.76))(ws@8.18.2))(openai@4.104.0(ws@8.18.2)(zod@3.25.76))
162 hono:
163 specifier: ^4.7.11
164 version: 4.8.0
@@ -375,7 +375,7 @@ importers:
375 version: 16.5.0
376 zod-to-json-schema:
377 specifier: ^3.24.5
378 - version: 3.24.5(zod@4.1.9)
378 + version: 3.24.5(zod@3.25.76)
379 devDependencies:
380 '@types/bun':
381 specifier: ^1.2.9
@@ -446,11 +446,39 @@ importers:
446 specifier: 'catalog:'
447 version: 5.9.2
448
449 + ts/examples/mcp:
450 + dependencies:
451 + '@ai-sdk/openai':
452 + specifier: ^2.0.35
453 + version: 2.0.35(zod@3.25.76)
454 + '@composio/core':
455 + specifier: workspace:*
456 + version: link:../../packages/core
457 + '@composio/vercel':
458 + specifier: workspace:*
459 + version: link:../../packages/providers/vercel
460 + '@modelcontextprotocol/sdk':
461 + specifier: ^1.18.0
462 + version: 1.18.0
463 + ai:
464 + specifier: 'catalog:'
465 + version: 5.0.44(zod@3.25.76)
466 + dotenv:
467 + specifier: ^16.4.1
468 + version: 16.6.1
469 + devDependencies:
470 + '@types/bun':
471 + specifier: ^1.2.9
472 + version: 1.2.16
473 + typescript:
474 + specifier: 'catalog:'
475 + version: 5.9.2
476 +
477 ts/examples/modifiers:
478 dependencies:
479 '@ai-sdk/openai':
480 specifier: ^1.3.16
453 - version: 1.3.22(zod@4.1.9)
481 + version: 1.3.22(zod@3.25.76)
482 '@composio/core':
483 specifier: workspace:*
484 version: link:../../packages/core
@@ -459,7 +487,7 @@ importers:
487 version: link:../../packages/providers/vercel
488 ai:
489 specifier: 'catalog:'
462 - version: 5.0.44(zod@4.1.9)
490 + version: 5.0.44(zod@3.25.76)
491 devDependencies:
492 '@types/bun':
493 specifier: ^1.2.9
@@ -483,8 +511,8 @@ importers:
511 specifier: ^1.18.0
512 version: 1.18.0
513 '@openai/agents':
486 - specifier: ^0.1.3
487 - version: 0.1.3(ws@8.18.2)(zod@3.25.76)
514 + specifier: ^0.1.4
515 + version: 0.1.4(ws@8.18.2)(zod@3.25.76)
516 dotenv:
517 specifier: ^16.4.1
518 version: 16.5.0
@@ -525,7 +553,7 @@ importers:
553 dependencies:
554 '@ai-sdk/openai':
555 specifier: ^1.3.16
528 - version: 1.3.22(zod@4.1.9)
556 + version: 1.3.22(zod@3.25.76)
557 '@composio/core':
558 specifier: workspace:*
559 version: link:../../packages/core
@@ -534,7 +562,7 @@ importers:
562 version: link:../../packages/providers/vercel
563 ai:
564 specifier: 'catalog:'
537 - version: 5.0.44(zod@4.1.9)
565 + version: 5.0.44(zod@3.25.76)
566 devDependencies:
567 '@types/bun':
568 specifier: ^1.2.9
@@ -553,10 +581,10 @@ importers:
581 version: 16.5.0
582 openai:
583 specifier: ^5.19.1
556 - version: 5.19.1(ws@8.18.2)(zod@4.1.9)
584 + version: 5.19.1(ws@8.18.2)(zod@3.25.76)
585 zod-to-json-schema:
586 specifier: ^3.24.5
559 - version: 3.24.5(zod@4.1.9)
587 + version: 3.24.5(zod@3.25.76)
588 devDependencies:
589 '@types/bun':
590 specifier: ^1.2.9
@@ -585,7 +613,7 @@ importers:
613 dependencies:
614 '@ai-sdk/openai':
615 specifier: ^2.0.16
588 - version: 2.0.16(zod@4.1.9)
616 + version: 2.0.16(zod@3.25.76)
617 '@composio/core':
618 specifier: workspace:*
619 version: link:../../packages/core
@@ -597,7 +625,7 @@ importers:
625 version: 1.18.0
626 ai:
627 specifier: 'catalog:'
600 - version: 5.0.44(zod@4.1.9)
628 + version: 5.0.44(zod@3.25.76)
629 dotenv:
630 specifier: ^16.5.0
631 version: 16.5.0
@@ -632,7 +660,7 @@ importers:
660 version: 1.0.0-alpha.1
661 '@composio/client':
662 specifier: 'catalog:'
635 - version: 0.1.0-alpha.36
663 + version: 0.1.0-alpha.37
664 '@composio/core':
665 specifier: workspace:*
666 version: link:../core
@@ -726,7 +754,7 @@ importers:
754 dependencies:
755 '@composio/client':
756 specifier: 'catalog:'
729 - version: 0.1.0-alpha.36
757 + version: 0.1.0-alpha.37
758 '@composio/json-schema-to-zod':
759 specifier: workspace:*
760 version: link:../json-schema-to-zod
@@ -802,7 +830,7 @@ importers:
830 version: 0.52.0
831 '@mastra/mcp':
832 specifier: ^0.12.0
805 - version: 0.12.0(@mastra/core@0.16.3(effect@3.16.16)(openapi-types@12.1.3)(react@18.3.1)(zod@4.1.9))(@types/json-schema@7.0.15)(zod@4.1.9)
833 + version: 0.12.0(@mastra/core@0.16.3(effect@3.16.16)(openapi-types@12.1.3)(react@18.3.1)(zod@3.25.76))(@types/json-schema@7.0.15)(zod@3.25.76)
834 devDependencies:
835 '@composio/core':
836 specifier: workspace:*
@@ -1015,6 +1043,12 @@ packages:
1043 peerDependencies:
1044 zod: ^3.25.76 || ^4
1045
1046 + '@ai-sdk/openai@2.0.35':
1047 + resolution: {integrity: sha512-LelCyotLQtL6lRYAvmtNvLyWirCR4YXr2aE4gXUXtpE+Y43eU1xdI3Jyq3Ugsvv2VhyKEceZRkrSFBmozrt21w==}
1048 + engines: {node: '>=18'}
1049 + peerDependencies:
1050 + zod: ^3.25.76 || ^4
1051 +
1052 '@ai-sdk/provider-utils@2.2.8':
1053 resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}
1054 engines: {node: '>=18'}
@@ -1216,8 +1250,8 @@ packages:
1250 '@cloudflare/workers-types@4.20250917.0':
1251 resolution: {integrity: sha512-Lsn9dZoRYZZCXXHZNa50cMP8kWhQZG9M7WjxNSiXFzC8bk4Wh/0SYYo4YINxEjEt6h2o69LmAhFaJ+qgaJTh8Q==}
1252
1219 - '@composio/client@0.1.0-alpha.36':
1220 - resolution: {integrity: sha512-YRsx5rRWFoT2kyzYTsJ5lDd6dZI2KmkLxdnaQdACc7A/DkFHzhZraSROaYLElYUP+2ScK4WynVU6+IaHzYn2KA==}
1253 + '@composio/client@0.1.0-alpha.37':
1254 + resolution: {integrity: sha512-2YzXiRXlxqOgEz7nEh1aKdJ9vwQRb69+RX6UH+LTDmuTwW+pOjI2qbhIBxTbP2z9e2SyHVG0/AtMxc9tR5jU0w==}
1255
1256 '@composio/google@0.1.52':
1257 resolution: {integrity: sha512-LrTOGR0vPo7/YWENGBfdB9cOt0C7uFxwISwv0gwu+8tSVsa7MgoZqREBpFA29E1Fb7ss1tlpAZusy4ojPeXKnQ==}
@@ -1800,138 +1834,163 @@ packages:
1834 resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==}
1835 cpu: [arm64]
1836 os: [linux]
1837 + libc: [glibc]
1838
1839 '@img/sharp-libvips-linux-arm64@1.1.0':
1840 resolution: {integrity: sha512-IVfGJa7gjChDET1dK9SekxFFdflarnUB8PwW8aGwEoF3oAsSDuNUTYS+SKDOyOJxQyDC1aPFMuRYLoDInyV9Ew==}
1841 cpu: [arm64]
1842 os: [linux]
1843 + libc: [glibc]
1844
1845 '@img/sharp-libvips-linux-arm@1.0.5':
1846 resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==}
1847 cpu: [arm]
1848 os: [linux]
1849 + libc: [glibc]
1850
1851 '@img/sharp-libvips-linux-arm@1.1.0':
1852 resolution: {integrity: sha512-s8BAd0lwUIvYCJyRdFqvsj+BJIpDBSxs6ivrOPm/R7piTs5UIwY5OjXrP2bqXC9/moGsyRa37eYWYCOGVXxVrA==}
1853 cpu: [arm]
1854 os: [linux]
1855 + libc: [glibc]
1856
1857 '@img/sharp-libvips-linux-ppc64@1.1.0':
1858 resolution: {integrity: sha512-tiXxFZFbhnkWE2LA8oQj7KYR+bWBkiV2nilRldT7bqoEZ4HiDOcePr9wVDAZPi/Id5fT1oY9iGnDq20cwUz8lQ==}
1859 cpu: [ppc64]
1860 os: [linux]
1861 + libc: [glibc]
1862
1863 '@img/sharp-libvips-linux-s390x@1.0.4':
1864 resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==}
1865 cpu: [s390x]
1866 os: [linux]
1867 + libc: [glibc]
1868
1869 '@img/sharp-libvips-linux-s390x@1.1.0':
1870 resolution: {integrity: sha512-xukSwvhguw7COyzvmjydRb3x/09+21HykyapcZchiCUkTThEQEOMtBj9UhkaBRLuBrgLFzQ2wbxdeCCJW/jgJA==}
1871 cpu: [s390x]
1872 os: [linux]
1873 + libc: [glibc]
1874
1875 '@img/sharp-libvips-linux-x64@1.0.4':
1876 resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==}
1877 cpu: [x64]
1878 os: [linux]
1879 + libc: [glibc]
1880
1881 '@img/sharp-libvips-linux-x64@1.1.0':
1882 resolution: {integrity: sha512-yRj2+reB8iMg9W5sULM3S74jVS7zqSzHG3Ol/twnAAkAhnGQnpjj6e4ayUz7V+FpKypwgs82xbRdYtchTTUB+Q==}
1883 cpu: [x64]
1884 os: [linux]
1885 + libc: [glibc]
1886
1887 '@img/sharp-libvips-linuxmusl-arm64@1.0.4':
1888 resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==}
1889 cpu: [arm64]
1890 os: [linux]
1891 + libc: [musl]
1892
1893 '@img/sharp-libvips-linuxmusl-arm64@1.1.0':
1894 resolution: {integrity: sha512-jYZdG+whg0MDK+q2COKbYidaqW/WTz0cc1E+tMAusiDygrM4ypmSCjOJPmFTvHHJ8j/6cAGyeDWZOsK06tP33w==}
1895 cpu: [arm64]
1896 os: [linux]
1897 + libc: [musl]
1898
1899 '@img/sharp-libvips-linuxmusl-x64@1.0.4':
1900 resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==}
1901 cpu: [x64]
1902 os: [linux]
1903 + libc: [musl]
1904
1905 '@img/sharp-libvips-linuxmusl-x64@1.1.0':
1906 resolution: {integrity: sha512-wK7SBdwrAiycjXdkPnGCPLjYb9lD4l6Ze2gSdAGVZrEL05AOUJESWU2lhlC+Ffn5/G+VKuSm6zzbQSzFX/P65A==}
1907 cpu: [x64]
1908 os: [linux]
1909 + libc: [musl]
1910
1911 '@img/sharp-linux-arm64@0.33.5':
1912 resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==}
1913 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1914 cpu: [arm64]
1915 os: [linux]
1916 + libc: [glibc]
1917
1918 '@img/sharp-linux-arm64@0.34.2':
1919 resolution: {integrity: sha512-D8n8wgWmPDakc83LORcfJepdOSN6MvWNzzz2ux0MnIbOqdieRZwVYY32zxVx+IFUT8er5KPcyU3XXsn+GzG/0Q==}
1920 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1921 cpu: [arm64]
1922 os: [linux]
1923 + libc: [glibc]
1924
1925 '@img/sharp-linux-arm@0.33.5':
1926 resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==}
1927 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1928 cpu: [arm]
1929 os: [linux]
1930 + libc: [glibc]
1931
1932 '@img/sharp-linux-arm@0.34.2':
1933 resolution: {integrity: sha512-0DZzkvuEOqQUP9mo2kjjKNok5AmnOr1jB2XYjkaoNRwpAYMDzRmAqUIa1nRi58S2WswqSfPOWLNOr0FDT3H5RQ==}
1934 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1935 cpu: [arm]
1936 os: [linux]
1937 + libc: [glibc]
1938
1939 '@img/sharp-linux-s390x@0.33.5':
1940 resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==}
1941 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1942 cpu: [s390x]
1943 os: [linux]
1944 + libc: [glibc]
1945
1946 '@img/sharp-linux-s390x@0.34.2':
1947 resolution: {integrity: sha512-EGZ1xwhBI7dNISwxjChqBGELCWMGDvmxZXKjQRuqMrakhO8QoMgqCrdjnAqJq/CScxfRn+Bb7suXBElKQpPDiw==}
1948 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1949 cpu: [s390x]
1950 os: [linux]
1951 + libc: [glibc]
1952
1953 '@img/sharp-linux-x64@0.33.5':
1954 resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==}
1955 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1956 cpu: [x64]
1957 os: [linux]
1958 + libc: [glibc]
1959
1960 '@img/sharp-linux-x64@0.34.2':
1961 resolution: {integrity: sha512-sD7J+h5nFLMMmOXYH4DD9UtSNBD05tWSSdWAcEyzqW8Cn5UxXvsHAxmxSesYUsTOBmUnjtxghKDl15EvfqLFbQ==}
1962 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1963 cpu: [x64]
1964 os: [linux]
1965 + libc: [glibc]
1966
1967 '@img/sharp-linuxmusl-arm64@0.33.5':
1968 resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==}
1969 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1970 cpu: [arm64]
1971 os: [linux]
1972 + libc: [musl]
1973
1974 '@img/sharp-linuxmusl-arm64@0.34.2':
1975 resolution: {integrity: sha512-NEE2vQ6wcxYav1/A22OOxoSOGiKnNmDzCYFOZ949xFmrWZOVII1Bp3NqVVpvj+3UeHMFyN5eP/V5hzViQ5CZNA==}
1976 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1977 cpu: [arm64]
1978 os: [linux]
1979 + libc: [musl]
1980
1981 '@img/sharp-linuxmusl-x64@0.33.5':
1982 resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==}
1983 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1984 cpu: [x64]
1985 os: [linux]
1986 + libc: [musl]
1987
1988 '@img/sharp-linuxmusl-x64@0.34.2':
1989 resolution: {integrity: sha512-DOYMrDm5E6/8bm/yQLCWyuDJwUnlevR8xtF8bs+gjZ7cyUNYXiSf/E8Kp0Ss5xasIaXSHzb888V1BE4i1hFhAA==}
1990 engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1991 cpu: [x64]
1992 os: [linux]
1993 + libc: [musl]
1994
1995 '@img/sharp-wasm32@0.33.5':
1996 resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==}
@@ -2229,24 +2288,28 @@ packages:
2288 engines: {node: '>= 10'}
2289 cpu: [arm64]
2290 os: [linux]
2291 + libc: [glibc]
2292
2293 '@next/swc-linux-arm64-musl@15.3.4':
2294 resolution: {integrity: sha512-wFyZ7X470YJQtpKot4xCY3gpdn8lE9nTlldG07/kJYexCUpX1piX+MBfZdvulo+t1yADFVEuzFfVHfklfEx8kw==}
2295 engines: {node: '>= 10'}
2296 cpu: [arm64]
2297 os: [linux]
2298 + libc: [musl]
2299
2300 '@next/swc-linux-x64-gnu@15.3.4':
2301 resolution: {integrity: sha512-gEbH9rv9o7I12qPyvZNVTyP/PWKqOp8clvnoYZQiX800KkqsaJZuOXkWgMa7ANCCh/oEN2ZQheh3yH8/kWPSEg==}
2302 engines: {node: '>= 10'}
2303 cpu: [x64]
2304 os: [linux]
2305 + libc: [glibc]
2306
2307 '@next/swc-linux-x64-musl@15.3.4':
2308 resolution: {integrity: sha512-Cf8sr0ufuC/nu/yQ76AnarbSAXcwG/wj+1xFPNbyNo8ltA6kw5d5YqO8kQuwVIxk13SBdtgXrNyom3ZosHAy4A==}
2309 engines: {node: '>= 10'}
2310 cpu: [x64]
2311 os: [linux]
2312 + libc: [musl]
2313
2314 '@next/swc-win32-arm64-msvc@15.3.4':
2315 resolution: {integrity: sha512-ay5+qADDN3rwRbRpEhTOreOn1OyJIXS60tg9WMYTWCy3fB6rGoyjLVxc4dR9PYjEdR2iDYsaF5h03NA+XuYPQQ==}
@@ -2280,21 +2343,44 @@ packages:
2343 zod:
2344 optional: true
2345
2346 + '@openai/agents-core@0.1.4':
2347 + resolution: {integrity: sha512-7GWq5qRaYVJ+NXx92MXLOpkUthVsW2SIsQZHH0U2uKZJlvwbYWKY/lJGSJ3Kg9CkATEhn+p5U0CugNk6k/eXXw==}
2348 + peerDependencies:
2349 + zod: ^3.25.40
2350 + peerDependenciesMeta:
2351 + zod:
2352 + optional: true
2353 +
2354 '@openai/agents-openai@0.1.3':
2355 resolution: {integrity: sha512-nyC+ShxxLtDtQrcAdpfegmrmOKou0jHPrl1iTFizo2f/KqeJ0n8OvNOmiixMxYgAOA2D3KqxdkHcgdAIQlH7TQ==}
2356 peerDependencies:
2357 zod: ^3.25.40
2358
2359 + '@openai/agents-openai@0.1.4':
2360 + resolution: {integrity: sha512-kHAjnXvpP4CLcHeswuhluRLgg6DnozW7wQgc8SUg9M1vzHfez+61ZhkijffhHTgzmGICLVFHrBrtDTvRqoSAcw==}
2361 + peerDependencies:
2362 + zod: ^3.25.40
2363 +
2364 '@openai/agents-realtime@0.1.3':
2365 resolution: {integrity: sha512-8uB63JuZkGew+Ccd+aZg2C4FkCRu3MpVg/+6veJzrYzjYsJx8ncUUTIYzDBs71m86+WJwlzmKv0pcGAzbMXx5g==}
2366 peerDependencies:
2367 zod: ^3.25.40
2368
2369 + '@openai/agents-realtime@0.1.4':
2370 + resolution: {integrity: sha512-d8DwwT/lCoXjWPr0/yT2/RQ35zqJa5aOf66YI6LJmBlHZp9RV7v/Jq81vuPQBK+CRK2LLe8UzBZHkZHTYY4m+Q==}
2371 + peerDependencies:
2372 + zod: ^3.25.40
2373 +
2374 '@openai/agents@0.1.3':
2375 resolution: {integrity: sha512-uGB831WPmUuJjCVIKbAcFMZLokkfSu/F7XSlbMs1mfCP1yD+47ZGQbn0C0PPiOoMN05dbmaq9tbYbjVYbruhDA==}
2376 peerDependencies:
2377 zod: ^3.25.40
2378
2379 + '@openai/agents@0.1.4':
2380 + resolution: {integrity: sha512-Zfo1I9SEKkbyBBjn8IsdXnYT+AOm7M1FuaS+oA6X+KouX4WjSR0oRTV5dmpv1F6VVyDg4hz6Ux1GvIi84gspEQ==}
2381 + peerDependencies:
2382 + zod: ^3.25.40
2383 +
2384 '@opentelemetry/api-logs@0.203.0':
2385 resolution: {integrity: sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==}
2386 engines: {node: '>=8.0.0'}
@@ -2787,36 +2873,42 @@ packages:
2873 engines: {node: '>= 10.0.0'}
2874 cpu: [arm]
2875 os: [linux]
2876 + libc: [glibc]
2877
2878 '@parcel/watcher-linux-arm-musl@2.5.1':
2879 resolution: {integrity: sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==}
2880 engines: {node: '>= 10.0.0'}
2881 cpu: [arm]
2882 os: [linux]
2883 + libc: [musl]
2884
2885 '@parcel/watcher-linux-arm64-glibc@2.5.1':
2886 resolution: {integrity: sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==}
2887 engines: {node: '>= 10.0.0'}
2888 cpu: [arm64]
2889 os: [linux]
2890 + libc: [glibc]
2891
2892 '@parcel/watcher-linux-arm64-musl@2.5.1':
2893 resolution: {integrity: sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==}
2894 engines: {node: '>= 10.0.0'}
2895 cpu: [arm64]
2896 os: [linux]
2897 + libc: [musl]
2898
2899 '@parcel/watcher-linux-x64-glibc@2.5.1':
2900 resolution: {integrity: sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==}
2901 engines: {node: '>= 10.0.0'}
2902 cpu: [x64]
2903 os: [linux]
2904 + libc: [glibc]
2905
2906 '@parcel/watcher-linux-x64-musl@2.5.1':
2907 resolution: {integrity: sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==}
2908 engines: {node: '>= 10.0.0'}
2909 cpu: [x64]
2910 os: [linux]
2911 + libc: [musl]
2912
2913 '@parcel/watcher-win32-arm64@2.5.1':
2914 resolution: {integrity: sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==}
@@ -2930,56 +3022,67 @@ packages:
3022 resolution: {integrity: sha512-gTJ/JnnjCMc15uwB10TTATBEhK9meBIY+gXP4s0sHD1zHOaIh4Dmy1X9wup18IiY9tTNk5gJc4yx9ctj/fjrIw==}
3023 cpu: [arm]
3024 os: [linux]
3025 + libc: [glibc]
3026
3027 '@rollup/rollup-linux-arm-musleabihf@4.43.0':
3028 resolution: {integrity: sha512-ZJ3gZynL1LDSIvRfz0qXtTNs56n5DI2Mq+WACWZ7yGHFUEirHBRt7fyIk0NsCKhmRhn7WAcjgSkSVVxKlPNFFw==}
3029 cpu: [arm]
3030 os: [linux]
3031 + libc: [musl]
3032
3033 '@rollup/rollup-linux-arm64-gnu@4.43.0':
3034 resolution: {integrity: sha512-8FnkipasmOOSSlfucGYEu58U8cxEdhziKjPD2FIa0ONVMxvl/hmONtX/7y4vGjdUhjcTHlKlDhw3H9t98fPvyA==}
3035 cpu: [arm64]
3036 os: [linux]
3037 + libc: [glibc]
3038
3039 '@rollup/rollup-linux-arm64-musl@4.43.0':
3040 resolution: {integrity: sha512-KPPyAdlcIZ6S9C3S2cndXDkV0Bb1OSMsX0Eelr2Bay4EsF9yi9u9uzc9RniK3mcUGCLhWY9oLr6er80P5DE6XA==}
3041 cpu: [arm64]
3042 os: [linux]
3043 + libc: [musl]
3044
3045 '@rollup/rollup-linux-loongarch64-gnu@4.43.0':
3046 resolution: {integrity: sha512-HPGDIH0/ZzAZjvtlXj6g+KDQ9ZMHfSP553za7o2Odegb/BEfwJcR0Sw0RLNpQ9nC6Gy8s+3mSS9xjZ0n3rhcYg==}
3047 cpu: [loong64]
3048 os: [linux]
3049 + libc: [glibc]
3050
3051 '@rollup/rollup-linux-powerpc64le-gnu@4.43.0':
3052 resolution: {integrity: sha512-gEmwbOws4U4GLAJDhhtSPWPXUzDfMRedT3hFMyRAvM9Mrnj+dJIFIeL7otsv2WF3D7GrV0GIewW0y28dOYWkmw==}
3053 cpu: [ppc64]
3054 os: [linux]
3055 + libc: [glibc]
3056
3057 '@rollup/rollup-linux-riscv64-gnu@4.43.0':
3058 resolution: {integrity: sha512-XXKvo2e+wFtXZF/9xoWohHg+MuRnvO29TI5Hqe9xwN5uN8NKUYy7tXUG3EZAlfchufNCTHNGjEx7uN78KsBo0g==}
3059 cpu: [riscv64]
3060 os: [linux]
3061 + libc: [glibc]
3062
3063 '@rollup/rollup-linux-riscv64-musl@4.43.0':
3064 resolution: {integrity: sha512-ruf3hPWhjw6uDFsOAzmbNIvlXFXlBQ4nk57Sec8E8rUxs/AI4HD6xmiiasOOx/3QxS2f5eQMKTAwk7KHwpzr/Q==}
3065 cpu: [riscv64]
3066 os: [linux]
3067 + libc: [musl]
3068
3069 '@rollup/rollup-linux-s390x-gnu@4.43.0':
3070 resolution: {integrity: sha512-QmNIAqDiEMEvFV15rsSnjoSmO0+eJLoKRD9EAa9rrYNwO/XRCtOGM3A5A0X+wmG+XRrw9Fxdsw+LnyYiZWWcVw==}
3071 cpu: [s390x]
3072 os: [linux]
3073 + libc: [glibc]
3074
3075 '@rollup/rollup-linux-x64-gnu@4.43.0':
3076 resolution: {integrity: sha512-jAHr/S0iiBtFyzjhOkAics/2SrXE092qyqEg96e90L3t9Op8OTzS6+IX0Fy5wCt2+KqeHAkti+eitV0wvblEoQ==}
3077 cpu: [x64]
3078 os: [linux]
3079 + libc: [glibc]
3080
3081 '@rollup/rollup-linux-x64-musl@4.43.0':
3082 resolution: {integrity: sha512-3yATWgdeXyuHtBhrLt98w+5fKurdqvs8B53LaoKD7P7H7FKOONLsBVMNl9ghPQZQuYcceV5CDyPfyfGpMWD9mQ==}
3083 cpu: [x64]
3084 os: [linux]
3085 + libc: [musl]
3086
3087 '@rollup/rollup-win32-arm64-msvc@4.43.0':
3088 resolution: {integrity: sha512-wVzXp2qDSCOpcBCT5WRWLmpJRIzv23valvcTwMHEobkjippNf+C3ys/+wf07poPkeNix0paTNemB2XrHr2TnGw==}
@@ -6489,47 +6592,29 @@ snapshots:
6592 '@ai-sdk/provider-utils': 3.0.7(zod@3.25.76)
6593 zod: 3.25.76
6594
6492 - '@ai-sdk/gateway@1.0.15(zod@4.1.9)':
6493 - dependencies:
6494 - '@ai-sdk/provider': 2.0.0
6495 - '@ai-sdk/provider-utils': 3.0.7(zod@4.1.9)
6496 - zod: 4.1.9
6497 -
6595 '@ai-sdk/gateway@1.0.23(zod@3.25.76)':
6596 dependencies:
6597 '@ai-sdk/provider': 2.0.0
6598 '@ai-sdk/provider-utils': 3.0.9(zod@3.25.76)
6599 zod: 3.25.76
6600
6504 - '@ai-sdk/gateway@1.0.23(zod@4.1.9)':
6505 - dependencies:
6506 - '@ai-sdk/provider': 2.0.0
6507 - '@ai-sdk/provider-utils': 3.0.9(zod@4.1.9)
6508 - zod: 4.1.9
6509 -
6601 '@ai-sdk/openai@1.3.22(zod@3.25.76)':
6602 dependencies:
6603 '@ai-sdk/provider': 1.1.3
6604 '@ai-sdk/provider-utils': 2.2.8(zod@3.25.76)
6605 zod: 3.25.76
6606
6516 - '@ai-sdk/openai@1.3.22(zod@4.1.9)':
6517 - dependencies:
6518 - '@ai-sdk/provider': 1.1.3
6519 - '@ai-sdk/provider-utils': 2.2.8(zod@4.1.9)
6520 - zod: 4.1.9
6521 -
6607 '@ai-sdk/openai@2.0.16(zod@3.25.76)':
6608 dependencies:
6609 '@ai-sdk/provider': 2.0.0
6610 '@ai-sdk/provider-utils': 3.0.4(zod@3.25.76)
6611 zod: 3.25.76
6612
6528 - '@ai-sdk/openai@2.0.16(zod@4.1.9)':
6613 + '@ai-sdk/openai@2.0.35(zod@3.25.76)':
6614 dependencies:
6615 '@ai-sdk/provider': 2.0.0
6531 - '@ai-sdk/provider-utils': 3.0.4(zod@4.1.9)
6532 - zod: 4.1.9
6616 + '@ai-sdk/provider-utils': 3.0.9(zod@3.25.76)
6617 + zod: 3.25.76
6618
6619 '@ai-sdk/provider-utils@2.2.8(zod@3.25.76)':
6620 dependencies:
@@ -6538,13 +6623,6 @@ snapshots:
6623 secure-json-parse: 2.7.0
6624 zod: 3.25.76
6625
6541 - '@ai-sdk/provider-utils@2.2.8(zod@4.1.9)':
6542 - dependencies:
6543 - '@ai-sdk/provider': 1.1.3
6544 - nanoid: 3.3.11
6545 - secure-json-parse: 2.7.0
6546 - zod: 4.1.9
6547 -
6626 '@ai-sdk/provider-utils@3.0.4(zod@3.25.76)':
6627 dependencies:
6628 '@ai-sdk/provider': 2.0.0
@@ -6553,14 +6631,6 @@ snapshots:
6631 zod: 3.25.76
6632 zod-to-json-schema: 3.24.6(zod@3.25.76)
6633
6556 - '@ai-sdk/provider-utils@3.0.4(zod@4.1.9)':
6557 - dependencies:
6558 - '@ai-sdk/provider': 2.0.0
6559 - '@standard-schema/spec': 1.0.0
6560 - eventsource-parser: 3.0.3
6561 - zod: 4.1.9
6562 - zod-to-json-schema: 3.24.6(zod@4.1.9)
6563 -
6634 '@ai-sdk/provider-utils@3.0.5(zod@3.25.76)':
6635 dependencies:
6636 '@ai-sdk/provider': 2.0.0
@@ -6569,14 +6639,6 @@ snapshots:
6639 zod: 3.25.76
6640 zod-to-json-schema: 3.24.6(zod@3.25.76)
6641
6572 - '@ai-sdk/provider-utils@3.0.5(zod@4.1.9)':
6573 - dependencies:
6574 - '@ai-sdk/provider': 2.0.0
6575 - '@standard-schema/spec': 1.0.0
6576 - eventsource-parser: 3.0.6
6577 - zod: 4.1.9
6578 - zod-to-json-schema: 3.24.6(zod@4.1.9)
6579 -
6642 '@ai-sdk/provider-utils@3.0.7(zod@3.25.76)':
6643 dependencies:
6644 '@ai-sdk/provider': 2.0.0
@@ -6584,13 +6646,6 @@ snapshots:
6646 eventsource-parser: 3.0.6
6647 zod: 3.25.76
6648
6587 - '@ai-sdk/provider-utils@3.0.7(zod@4.1.9)':
6588 - dependencies:
6589 - '@ai-sdk/provider': 2.0.0
6590 - '@standard-schema/spec': 1.0.0
6591 - eventsource-parser: 3.0.6
6592 - zod: 4.1.9
6593 -
6649 '@ai-sdk/provider-utils@3.0.9(zod@3.25.76)':
6650 dependencies:
6651 '@ai-sdk/provider': 2.0.0
@@ -6598,13 +6653,6 @@ snapshots:
6653 eventsource-parser: 3.0.6
6654 zod: 3.25.76
6655
6601 - '@ai-sdk/provider-utils@3.0.9(zod@4.1.9)':
6602 - dependencies:
6603 - '@ai-sdk/provider': 2.0.0
6604 - '@standard-schema/spec': 1.0.0
6605 - eventsource-parser: 3.0.6
6606 - zod: 4.1.9
6607 -
6656 '@ai-sdk/provider@1.1.3':
6657 dependencies:
6658 json-schema: 0.4.0
@@ -6623,16 +6671,6 @@ snapshots:
6671 optionalDependencies:
6672 zod: 3.25.76
6673
6626 - '@ai-sdk/react@1.2.12(react@18.3.1)(zod@4.1.9)':
6627 - dependencies:
6628 - '@ai-sdk/provider-utils': 2.2.8(zod@4.1.9)
6629 - '@ai-sdk/ui-utils': 1.2.11(zod@4.1.9)
6630 - react: 18.3.1
6631 - swr: 2.3.3(react@18.3.1)
6632 - throttleit: 2.1.0
6633 - optionalDependencies:
6634 - zod: 4.1.9
6635 -
6674 '@ai-sdk/ui-utils@1.2.11(zod@3.25.76)':
6675 dependencies:
6676 '@ai-sdk/provider': 1.1.3
@@ -6640,13 +6678,6 @@ snapshots:
6678 zod: 3.25.76
6679 zod-to-json-schema: 3.24.6(zod@3.25.76)
6680
6643 - '@ai-sdk/ui-utils@1.2.11(zod@4.1.9)':
6644 - dependencies:
6645 - '@ai-sdk/provider': 1.1.3
6646 - '@ai-sdk/provider-utils': 2.2.8(zod@4.1.9)
6647 - zod: 4.1.9
6648 - zod-to-json-schema: 3.24.6(zod@4.1.9)
6649 -
6681 '@alloc/quick-lru@5.2.0': {}
6682
6683 '@anthropic-ai/sdk@0.52.0': {}
@@ -6871,7 +6902,7 @@ snapshots:
6902
6903 '@cloudflare/workers-types@4.20250917.0': {}
6904
6874 - '@composio/client@0.1.0-alpha.36': {}
6905 + '@composio/client@0.1.0-alpha.37': {}
6906
6907 '@composio/google@0.1.52(@composio/core@ts+packages+core)(@google/genai@1.19.0(@modelcontextprotocol/sdk@1.18.0))':
6908 dependencies:
@@ -7761,63 +7792,6 @@ snapshots:
7792 - valibot
7793 - zod-openapi
7794
7764 - '@mastra/core@0.16.3(effect@3.16.16)(openapi-types@12.1.3)(react@18.3.1)(zod@4.1.9)':
7765 - dependencies:
7766 - '@a2a-js/sdk': 0.2.5
7767 - '@ai-sdk/provider': 1.1.3
7768 - '@ai-sdk/provider-utils': 2.2.8(zod@4.1.9)
7769 - '@ai-sdk/provider-utils-v5': '@ai-sdk/provider-utils@3.0.5(zod@4.1.9)'
7770 - '@ai-sdk/provider-v5': '@ai-sdk/provider@2.0.0'
7771 - '@ai-sdk/ui-utils': 1.2.11(zod@4.1.9)
7772 - '@mastra/schema-compat': 0.11.3(ai@4.3.19(react@18.3.1)(zod@4.1.9))(zod@4.1.9)
7773 - '@opentelemetry/api': 1.9.0
7774 - '@opentelemetry/auto-instrumentations-node': 0.62.1(@opentelemetry/api@1.9.0)(@opentelemetry/core@2.0.1(@opentelemetry/api@1.9.0))
7775 - '@opentelemetry/core': 2.0.1(@opentelemetry/api@1.9.0)
7776 - '@opentelemetry/exporter-trace-otlp-grpc': 0.203.0(@opentelemetry/api@1.9.0)
7777 - '@opentelemetry/exporter-trace-otlp-http': 0.203.0(@opentelemetry/api@1.9.0)
7778 - '@opentelemetry/otlp-exporter-base': 0.203.0(@opentelemetry/api@1.9.0)
7779 - '@opentelemetry/otlp-transformer': 0.203.0(@opentelemetry/api@1.9.0)
7780 - '@opentelemetry/resources': 2.0.1(@opentelemetry/api@1.9.0)
7781 - '@opentelemetry/sdk-metrics': 2.0.1(@opentelemetry/api@1.9.0)
7782 - '@opentelemetry/sdk-node': 0.203.0(@opentelemetry/api@1.9.0)
7783 - '@opentelemetry/sdk-trace-base': 2.0.1(@opentelemetry/api@1.9.0)
7784 - '@opentelemetry/sdk-trace-node': 2.0.1(@opentelemetry/api@1.9.0)
7785 - '@opentelemetry/semantic-conventions': 1.36.0
7786 - '@sindresorhus/slugify': 2.2.1
7787 - ai: 4.3.19(react@18.3.1)(zod@4.1.9)
7788 - ai-v5: ai@5.0.28(zod@4.1.9)
7789 - date-fns: 3.6.0
7790 - dotenv: 16.6.1
7791 - hono: 4.9.7
7792 - hono-openapi: 0.4.8(effect@3.16.16)(hono@4.9.7)(openapi-types@12.1.3)(zod@4.1.9)
7793 - js-tiktoken: 1.0.20
7794 - json-schema: 0.4.0
7795 - json-schema-to-zod: 2.6.1
7796 - p-map: 7.0.3
7797 - pino: 9.7.0
7798 - pino-pretty: 13.0.0
7799 - radash: 12.1.1
7800 - sift: 17.1.3
7801 - xstate: 5.20.2
7802 - zod: 4.1.9
7803 - zod-to-json-schema: 3.24.6(zod@4.1.9)
7804 - transitivePeerDependencies:
7805 - - '@hono/arktype-validator'
7806 - - '@hono/effect-validator'
7807 - - '@hono/typebox-validator'
7808 - - '@hono/valibot-validator'
7809 - - '@hono/zod-validator'
7810 - - '@sinclair/typebox'
7811 - - '@valibot/to-json-schema'
7812 - - arktype
7813 - - effect
7814 - - encoding
7815 - - openapi-types
7816 - - react
7817 - - supports-color
7818 - - valibot
7819 - - zod-openapi
7820 -
7795 '@mastra/mcp@0.12.0(@mastra/core@0.16.3(effect@3.16.16)(openapi-types@12.1.3)(react@18.3.1)(zod@3.25.76))(@types/json-schema@7.0.15)(zod@3.25.76)':
7796 dependencies:
7797 '@apidevtools/json-schema-ref-parser': 14.2.1(@types/json-schema@7.0.15)
@@ -7834,22 +7808,6 @@ snapshots:
7808 - '@types/json-schema'
7809 - supports-color
7810
7837 - '@mastra/mcp@0.12.0(@mastra/core@0.16.3(effect@3.16.16)(openapi-types@12.1.3)(react@18.3.1)(zod@4.1.9))(@types/json-schema@7.0.15)(zod@4.1.9)':
7838 - dependencies:
7839 - '@apidevtools/json-schema-ref-parser': 14.2.1(@types/json-schema@7.0.15)
7840 - '@mastra/core': 0.16.3(effect@3.16.16)(openapi-types@12.1.3)(react@18.3.1)(zod@4.1.9)
7841 - '@modelcontextprotocol/sdk': 1.18.0
7842 - date-fns: 4.1.0
7843 - exit-hook: 4.0.0
7844 - fast-deep-equal: 3.1.3
7845 - uuid: 11.1.0
7846 - zod: 4.1.9
7847 - zod-from-json-schema: 0.5.0
7848 - zod-from-json-schema-v3: zod-from-json-schema@0.0.5
7849 - transitivePeerDependencies:
7850 - - '@types/json-schema'
7851 - - supports-color
7852 -
7811 '@mastra/schema-compat@0.11.3(ai@4.3.19(react@18.3.1)(zod@3.25.76))(zod@3.25.76)':
7812 dependencies:
7813 ai: 4.3.19(react@18.3.1)(zod@3.25.76)
@@ -7859,15 +7817,6 @@ snapshots:
7817 zod-from-json-schema-v3: zod-from-json-schema@0.0.5
7818 zod-to-json-schema: 3.24.6(zod@3.25.76)
7819
7862 - '@mastra/schema-compat@0.11.3(ai@4.3.19(react@18.3.1)(zod@4.1.9))(zod@4.1.9)':
7863 - dependencies:
7864 - ai: 4.3.19(react@18.3.1)(zod@4.1.9)
7865 - json-schema: 0.4.0
7866 - zod: 4.1.9
7867 - zod-from-json-schema: 0.5.0
7868 - zod-from-json-schema-v3: zod-from-json-schema@0.0.5
7869 - zod-to-json-schema: 3.24.6(zod@4.1.9)
7870 -
7820 '@modelcontextprotocol/sdk@1.18.0':
7821 dependencies:
7822 ajv: 6.12.6
@@ -7952,6 +7901,17 @@ snapshots:
7901 - supports-color
7902 - ws
7903
7904 + '@openai/agents-core@0.1.4(ws@8.18.2)(zod@3.25.76)':
7905 + dependencies:
7906 + debug: 4.4.1(supports-color@10.0.0)
7907 + openai: 5.20.3(ws@8.18.2)(zod@3.25.76)
7908 + optionalDependencies:
7909 + '@modelcontextprotocol/sdk': 1.18.0
7910 + zod: 3.25.76
7911 + transitivePeerDependencies:
7912 + - supports-color
7913 + - ws
7914 +
7915 '@openai/agents-openai@0.1.3(ws@8.18.2)(zod@3.25.76)':
7916 dependencies:
7917 '@openai/agents-core': 0.1.3(ws@8.18.2)(zod@3.25.76)
@@ -7962,6 +7922,16 @@ snapshots:
7922 - supports-color
7923 - ws
7924
7925 + '@openai/agents-openai@0.1.4(ws@8.18.2)(zod@3.25.76)':
7926 + dependencies:
7927 + '@openai/agents-core': 0.1.4(ws@8.18.2)(zod@3.25.76)
7928 + debug: 4.4.1(supports-color@10.0.0)
7929 + openai: 5.20.3(ws@8.18.2)(zod@3.25.76)
7930 + zod: 3.25.76
7931 + transitivePeerDependencies:
7932 + - supports-color
7933 + - ws
7934 +
7935 '@openai/agents-realtime@0.1.3(zod@3.25.76)':
7936 dependencies:
7937 '@openai/agents-core': 0.1.3(ws@8.18.2)(zod@3.25.76)
@@ -7974,6 +7944,18 @@ snapshots:
7944 - supports-color
7945 - utf-8-validate
7946
7947 + '@openai/agents-realtime@0.1.4(zod@3.25.76)':
7948 + dependencies:
7949 + '@openai/agents-core': 0.1.4(ws@8.18.2)(zod@3.25.76)
7950 + '@types/ws': 8.18.1
7951 + debug: 4.4.1(supports-color@10.0.0)
7952 + ws: 8.18.2
7953 + zod: 3.25.76
7954 + transitivePeerDependencies:
7955 + - bufferutil
7956 + - supports-color
7957 + - utf-8-validate
7958 +
7959 '@openai/agents@0.1.3(ws@8.18.2)(zod@3.25.76)':
7960 dependencies:
7961 '@openai/agents-core': 0.1.3(ws@8.18.2)(zod@3.25.76)
@@ -7988,6 +7970,20 @@ snapshots:
7970 - utf-8-validate
7971 - ws
7972
7973 + '@openai/agents@0.1.4(ws@8.18.2)(zod@3.25.76)':
7974 + dependencies:
7975 + '@openai/agents-core': 0.1.4(ws@8.18.2)(zod@3.25.76)
7976 + '@openai/agents-openai': 0.1.4(ws@8.18.2)(zod@3.25.76)
7977 + '@openai/agents-realtime': 0.1.4(zod@3.25.76)
7978 + debug: 4.4.1(supports-color@10.0.0)
7979 + openai: 5.20.3(ws@8.18.2)(zod@3.25.76)
7980 + zod: 3.25.76
7981 + transitivePeerDependencies:
7982 + - bufferutil
7983 + - supports-color
7984 + - utf-8-validate
7985 + - ws
7986 +
7987 '@opentelemetry/api-logs@0.203.0':
7988 dependencies:
7989 '@opentelemetry/api': 1.9.0
@@ -9171,14 +9167,6 @@ snapshots:
9167 chai: 5.2.0
9168 tinyrainbow: 2.0.0
9169
9174 - '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.0))':
9175 - dependencies:
9176 - '@vitest/spy': 3.2.4
9177 - estree-walker: 3.0.3
9178 - magic-string: 0.30.17
9179 - optionalDependencies:
9180 - vite: 6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.0)
9181 -
9170 '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1))':
9171 dependencies:
9172 '@vitest/spy': 3.2.4
@@ -9187,14 +9175,6 @@ snapshots:
9175 optionalDependencies:
9176 vite: 6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1)
9177
9190 - '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1))':
9191 - dependencies:
9192 - '@vitest/spy': 3.2.4
9193 - estree-walker: 3.0.3
9194 - magic-string: 0.30.17
9195 - optionalDependencies:
9196 - vite: 6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1)
9197 -
9178 '@vitest/pretty-format@3.2.4':
9179 dependencies:
9180 tinyrainbow: 2.0.0
@@ -9224,7 +9204,7 @@ snapshots:
9204 sirv: 3.0.1
9205 tinyglobby: 0.2.14
9206 tinyrainbow: 2.0.0
9227 - vitest: 3.2.4(@types/node@20.19.1)(@vitest/ui@3.2.4)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.0)
9207 + vitest: 3.2.4(@types/node@22.15.32)(@vitest/ui@3.2.4)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1)
9208
9209 '@vitest/utils@3.2.4':
9210 dependencies:
@@ -9278,18 +9258,6 @@ snapshots:
9258 optionalDependencies:
9259 react: 18.3.1
9260
9281 - ai@4.3.19(react@18.3.1)(zod@4.1.9):
9282 - dependencies:
9283 - '@ai-sdk/provider': 1.1.3
9284 - '@ai-sdk/provider-utils': 2.2.8(zod@4.1.9)
9285 - '@ai-sdk/react': 1.2.12(react@18.3.1)(zod@4.1.9)
9286 - '@ai-sdk/ui-utils': 1.2.11(zod@4.1.9)
9287 - '@opentelemetry/api': 1.9.0
9288 - jsondiffpatch: 0.6.0
9289 - zod: 4.1.9
9290 - optionalDependencies:
9291 - react: 18.3.1
9292 -
9261 ai@5.0.28(zod@3.25.76):
9262 dependencies:
9263 '@ai-sdk/gateway': 1.0.15(zod@3.25.76)
@@ -9298,14 +9266,6 @@ snapshots:
9266 '@opentelemetry/api': 1.9.0
9267 zod: 3.25.76
9268
9301 - ai@5.0.28(zod@4.1.9):
9302 - dependencies:
9303 - '@ai-sdk/gateway': 1.0.15(zod@4.1.9)
9304 - '@ai-sdk/provider': 2.0.0
9305 - '@ai-sdk/provider-utils': 3.0.7(zod@4.1.9)
9306 - '@opentelemetry/api': 1.9.0
9307 - zod: 4.1.9
9308 -
9269 ai@5.0.44(zod@3.25.76):
9270 dependencies:
9271 '@ai-sdk/gateway': 1.0.23(zod@3.25.76)
@@ -9314,14 +9274,6 @@ snapshots:
9274 '@opentelemetry/api': 1.9.0
9275 zod: 3.25.76
9276
9317 - ai@5.0.44(zod@4.1.9):
9318 - dependencies:
9319 - '@ai-sdk/gateway': 1.0.23(zod@4.1.9)
9320 - '@ai-sdk/provider': 2.0.0
9321 - '@ai-sdk/provider-utils': 3.0.9(zod@4.1.9)
9322 - '@opentelemetry/api': 1.9.0
9323 - zod: 4.1.9
9324 -
9277 ajv@6.12.6:
9278 dependencies:
9279 fast-deep-equal: 3.1.3
@@ -9629,9 +9581,9 @@ snapshots:
9581 has-own-prop: 2.0.0
9582 repeat-string: 1.6.1
9583
9632 - composio-core@0.5.39(@ai-sdk/openai@2.0.16(zod@3.25.76))(@cloudflare/workers-types@4.20250917.0)(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@langchain/openai@0.5.13(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(ws@8.18.2))(ai@5.0.44(zod@3.25.76))(langchain@0.3.28(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@opentelemetry/api@1.9.0)(@opentelemetry/exporter-trace-otlp-proto@0.203.0(@opentelemetry/api@1.9.0))(@opentelemetry/sdk-trace-base@2.0.1(@opentelemetry/api@1.9.0))(axios@1.10.0)(openai@4.104.0(ws@8.18.2)(zod@3.25.76))(ws@8.18.2))(openai@4.104.0(ws@8.18.2)(zod@3.25.76)):
9584 + composio-core@0.5.39(@ai-sdk/openai@2.0.35(zod@3.25.76))(@cloudflare/workers-types@4.20250917.0)(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@langchain/openai@0.5.13(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(ws@8.18.2))(ai@5.0.44(zod@3.25.76))(langchain@0.3.28(@langchain/core@0.3.63(openai@4.104.0(ws@8.18.2)(zod@3.25.76)))(@opentelemetry/api@1.9.0)(@opentelemetry/exporter-trace-otlp-proto@0.203.0(@opentelemetry/api@1.9.0))(@opentelemetry/sdk-trace-base@2.0.1(@opentelemetry/api@1.9.0))(axios@1.10.0)(openai@4.104.0(ws@8.18.2)(zod@3.25.76))(ws@8.18.2))(openai@4.104.0(ws@8.18.2)(zod@3.25.76)):
9585 dependencies:
9634 - '@ai-sdk/openai': 2.0.16(zod@3.25.76)
9586 + '@ai-sdk/openai': 2.0.35(zod@3.25.76)
9587 '@cloudflare/workers-types': 4.20250917.0
9588 '@composio/mcp': 1.0.3-0
9589 '@hey-api/client-axios': 0.2.12(axios@1.10.0)
@@ -10450,15 +10402,6 @@ snapshots:
10402 hono: 4.9.7
10403 zod: 3.25.76
10404
10453 - hono-openapi@0.4.8(effect@3.16.16)(hono@4.9.7)(openapi-types@12.1.3)(zod@4.1.9):
10454 - dependencies:
10455 - json-schema-walker: 2.0.0
10456 - openapi-types: 12.1.3
10457 - optionalDependencies:
10458 - effect: 3.16.16
10459 - hono: 4.9.7
10460 - zod: 4.1.9
10461 -
10405 hono@4.8.0: {}
10406
10407 hono@4.9.7: {}
@@ -11107,10 +11050,10 @@ snapshots:
11050 ws: 8.18.2
11051 zod: 3.25.76
11052
11110 - openai@5.19.1(ws@8.18.2)(zod@4.1.9):
11053 + openai@5.19.1(ws@8.18.2)(zod@3.25.76):
11054 optionalDependencies:
11055 ws: 8.18.2
11113 - zod: 4.1.9
11056 + zod: 3.25.76
11057
11058 openai@5.20.3(ws@8.18.2)(zod@3.25.76):
11059 optionalDependencies:
@@ -12342,7 +12285,7 @@ snapshots:
12285 dependencies:
12286 '@types/chai': 5.2.2
12287 '@vitest/expect': 3.2.4
12345 - '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.0))
12288 + '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1))
12289 '@vitest/pretty-format': 3.2.4
12290 '@vitest/runner': 3.2.4
12291 '@vitest/snapshot': 3.2.4
@@ -12426,7 +12369,7 @@ snapshots:
12369 dependencies:
12370 '@types/chai': 5.2.2
12371 '@vitest/expect': 3.2.4
12429 - '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1))
12372 + '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.5)(yaml@2.8.1))
12373 '@vitest/pretty-format': 3.2.4
12374 '@vitest/runner': 3.2.4
12375 '@vitest/snapshot': 3.2.4
@@ -12621,18 +12564,10 @@ snapshots:
12564 dependencies:
12565 zod: 3.25.76
12566
12624 - zod-to-json-schema@3.24.5(zod@4.1.9):
12625 - dependencies:
12626 - zod: 4.1.9
12627 -
12567 zod-to-json-schema@3.24.6(zod@3.25.76):
12568 dependencies:
12569 zod: 3.25.76
12570
12632 - zod-to-json-schema@3.24.6(zod@4.1.9):
12633 - dependencies:
12634 - zod: 4.1.9
12635 -
12571 zod@3.22.3: {}
12572
12573 zod@3.25.32: {}
pnpm-workspace.yaml
+26 -30
@@ -1,35 +1,31 @@
1 packages:
2 -- "ts/packages/core"
3 -- "ts/packages/cli"
4 -- "ts/packages/json-schema-to-zod"
5 -- "ts/packages/providers/*"
6 -- "ts/packages/ts-builders"
7 -- "ts/packages/wrappers/*"
8 -- "ts/examples/*"
9 -- "fern"
10 -- "fern/llms-txt-worker"
11 -- "fern/pages/examples/*"
12 -- "fern/snippets/*"
2 + - ts/packages/core
3 + - ts/packages/cli
4 + - ts/packages/json-schema-to-zod
5 + - ts/packages/providers/*
6 + - ts/packages/ts-builders
7 + - ts/packages/wrappers/*
8 + - ts/examples/*
9 + - fern
10 + - fern/llms-txt-worker
11 + - fern/pages/examples/*
12 + - fern/snippets/*
13
14 -# See: https://pnpm.io/catalogs
14 catalog:
16 - "@composio/client": 0.1.0-alpha.36
17 - "@cloudflare/vitest-pool-workers": ^0.9.2
18 - "@cloudflare/workers-types": ^4.20250917.0
19 - "ai": ^5.0.44
20 - "openai": ^5.20.3
21 - "uuid": ^13.0.0
22 - "tsup": ^8.5.0
23 - "tsx": ^4.20.5
24 - "typescript": ^5.9.2
25 - "vitest": ^3.2.4
26 - "wrangler": ^4.37.0
15 + '@cloudflare/vitest-pool-workers': ^0.9.2
16 + '@cloudflare/workers-types': ^4.20250917.0
17 + '@composio/client': 0.1.0-alpha.37
18 + ai: 5.0.44
19 + openai: ^5.20.3
20 + tsup: ^8.5.0
21 + tsx: ^4.20.5
22 + typescript: ^5.9.2
23 + uuid: ^13.0.0
24 + vitest: ^3.2.4
25 + wrangler: ^4.37.0
26 + zod: 3.25.76
27
28 - # According to https://github.com/langchain-ai/langchainjs/issues/8468, v3.25.75 is broken. v3.25.76 is probably broken as well,
29 - # as it causes "error TS2589: Type instantiation is excessively deep and possibly infinite." in `./ts/packages/providers/langchain/src/index.ts`.
30 - # However, most packages imported elsewhere (e.g., ´@ai-sdk/*`) require `zod: ^3.25.76 || ^4`.
31 - # Hence, we have to use at least v3.25.76 for now, and "accept" and ignore the above TS2589 error in `@composio/langchain`.
32 - "zod": 3.25.76
28 +minimumReleaseAge: 1440
29
34 -# See: https://pnpm.io/settings#minimumreleaseage
35 -minimumReleaseAge: 1440 # 1 day
30 +minimumReleaseAgeExclude:
31 + - '@composio/client'
python/composio/core/models/__init__.py
+2
@@ -1,5 +1,6 @@
1 from .auth_configs import AuthConfigs
2 from .connected_accounts import ConnectedAccounts
3 +from .mcp import MCP
4 from .toolkits import Toolkits
5 from .tools import Tools
6 from .triggers import Triggers
@@ -7,6 +8,7 @@ from .triggers import Triggers
8 __all__ = [
9 "AuthConfigs",
10 "ConnectedAccounts",
11 + "MCP",
12 "Toolkits",
13 "Tools",
14 "Triggers",
python/composio/core/models/mcp.py new
+468
@@ -0,0 +1,468 @@
1 +"""
2 +MCP (Model Control Protocol) module for Composio SDK.
3 +
4 +This module provides MCP server operations
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +import typing as t
10 +
11 +import typing_extensions as te
12 +
13 +from composio_client import omit
14 +from composio_client.types.mcp.custom_create_response import CustomCreateResponse
15 +from composio.client import HttpClient
16 +from composio.core.models.base import Resource
17 +from composio.core.types import MCPToolkitConfig
18 +from composio.exceptions import ValidationError
19 +
20 +
21 +# Data Types (matching TypeScript specification)
22 +
23 +
24 +class MCPServerInstance(te.TypedDict):
25 + """MCP Server Instance data structure (matching TypeScript implementation)."""
26 +
27 + id: str
28 + name: str
29 + type: str
30 + url: str # User-specific connection URL
31 + user_id: str # Associated user ID
32 + allowed_tools: t.List[str] # Available tools for the user
33 + auth_configs: t.List[str] # Associated auth configurations
34 +
35 +
36 +class MCPItem(te.TypedDict):
37 + """Complete MCP server information."""
38 +
39 + id: str # Unique server identifier
40 + name: str # Human-readable server name
41 + allowed_tools: t.List[str] # Array of enabled tool identifiers
42 + auth_config_ids: t.List[str] # Array of auth configuration IDs
43 + toolkits: t.List[str] # Array of toolkit names
44 + commands: t.Dict[str, str] # Setup commands for different clients
45 + mcp_url: str # Server connection URL
46 + toolkit_icons: t.Dict[str, str] # Map of toolkit icons
47 + server_instance_count: int # Number of active instances
48 + created_at: te.NotRequired[t.Optional[str]]
49 + updated_at: te.NotRequired[t.Optional[str]]
50 +
51 +
52 +class MCPListResponse(te.TypedDict):
53 + """Paginated list response."""
54 +
55 + items: t.List[t.Any] # Array of MCP server objects (raw API response)
56 + current_page: int # Current page number
57 + total_pages: int # Total number of pages
58 +
59 +
60 +def _add_generate_method(
61 + response: CustomCreateResponse, mcp_instance: "MCP"
62 +) -> CustomCreateResponse:
63 + """Add generate method to CustomCreateResponse object."""
64 +
65 + def generate(
66 + user_id: str, manually_manage_connections: t.Optional[bool] = None
67 + ) -> MCPServerInstance:
68 + """
69 + Generate server instance for this MCP configuration.
70 + Matches TypeScript server.generate(userId) method.
71 +
72 + :param user_id: External user ID from your database
73 + :param manually_manage_connections: Whether to manually manage connections (optional)
74 + :return: MCP server instance
75 + """
76 + return mcp_instance.generate(user_id, response.id, manually_manage_connections)
77 +
78 + # Add the generate method to the response object
79 + response.generate = generate
80 + return response
81 +
82 +
83 +class MCP(Resource):
84 + """
85 + MCP (Model Control Protocol) class.
86 + Provides enhanced MCP server operations
87 +
88 + This matches the TypeScript ExperimentalMCP class functionality.
89 + """
90 +
91 + def __init__(self, client: HttpClient):
92 + """
93 + Initialize MCP instance.
94 +
95 + :param client: HTTP client for API calls
96 + """
97 + super().__init__(client)
98 +
99 + def create(
100 + self,
101 + name: str,
102 + toolkits: t.List[t.Union[MCPToolkitConfig, str]],
103 + manually_manage_connections: bool = False,
104 + allowed_tools: t.Optional[t.List[str]] = None,
105 + ) -> CustomCreateResponse:
106 + """
107 + Create a new MCP server configuration with specified toolkits and authentication settings.
108 +
109 + :param name: Unique name for the MCP configuration
110 + :param toolkits: List of toolkit configurations. Can be either:
111 + - MCPToolkitConfig objects with detailed configuration
112 + - Strings representing toolkit names (for simple cases)
113 + :param manually_manage_connections: Whether to manually manage account connections (default: False)
114 + :param allowed_tools: List of specific tools to enable across all toolkits (default: None for all tools)
115 + :return: Created server details with generate method
116 +
117 + Examples:
118 + >>> # Using toolkit configuration objects with auth
119 + >>> server = composio.experimental.mcp.create(
120 + ... 'personal-mcp-server',
121 + ... toolkits=[
122 + ... {
123 + ... 'toolkit': 'github',
124 + ... 'auth_config_id': 'ac_xyz',
125 + ... },
126 + ... {
127 + ... 'toolkit': 'slack',
128 + ... 'auth_config_id': 'ac_abc',
129 + ... },
130 + ... ],
131 + ... allowed_tools=['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
132 + ... manually_manage_connections=False
133 + ... )
134 + >>>
135 + >>> # Using simple toolkit names (most common usage)
136 + >>> server = composio.experimental.mcp.create(
137 + ... 'simple-mcp-server',
138 + ... toolkits=['composio_search', 'text_to_pdf'],
139 + ... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
140 + ... )
141 + >>>
142 + >>> # Using all tools from toolkits (default behavior)
143 + >>> server = composio.experimental.mcp.create(
144 + ... 'all-tools-server',
145 + ... toolkits=['composio_search', 'text_to_pdf']
146 + ... # allowed_tools=None means all tools from these toolkits
147 + ... )
148 + >>>
149 + >>> # Get server instance for a user
150 + >>> mcp = server.generate('user_12345')
151 + """
152 + if not toolkits:
153 + raise ValidationError("At least one toolkit configuration is required")
154 +
155 + try:
156 + # Normalize toolkits to MCPToolkitConfig format
157 + normalized_toolkit_configs = []
158 + for toolkit in toolkits:
159 + if isinstance(toolkit, str):
160 + # Convert string to MCPToolkitConfig
161 + normalized_toolkit_configs.append({"toolkit": toolkit})
162 + else:
163 + # Already MCPToolkitConfig, use as-is
164 + normalized_toolkit_configs.append(toolkit)
165 +
166 + # Extract toolkits and prepare for API call
167 + toolkit_configs = normalized_toolkit_configs
168 +
169 + # Get unique toolkits and auth config IDs
170 + toolkit_names = []
171 + auth_config_ids = []
172 +
173 + for toolkit_config in toolkit_configs:
174 + if (
175 + "toolkit" in toolkit_config
176 + and toolkit_config["toolkit"] not in toolkit_names
177 + ):
178 + toolkit_names.append(toolkit_config["toolkit"])
179 +
180 + if (
181 + "auth_config_id" in toolkit_config
182 + and toolkit_config["auth_config_id"] not in auth_config_ids
183 + ):
184 + auth_config_ids.append(toolkit_config["auth_config_id"])
185 +
186 + # Use the allowed_tools parameter instead of individual toolkit configs
187 + custom_tools = allowed_tools if allowed_tools is not None else omit
188 +
189 + # Use the custom MCP create endpoint
190 + response = self._client.mcp.custom.create(
191 + name=name,
192 + toolkits=toolkit_names,
193 + auth_config_ids=auth_config_ids,
194 + custom_tools=custom_tools,
195 + managed_auth_via_composio=not manually_manage_connections,
196 + )
197 +
198 + # Return response with generate method (matching TypeScript behavior)
199 + return _add_generate_method(response, self)
200 +
201 + except Exception as e:
202 + raise ValidationError("Failed to create MCP server") from e
203 +
204 + def list(
205 + self,
206 + page_no: t.Optional[int] = None,
207 + limit: t.Optional[int] = None,
208 + toolkits: t.Optional[str] = None,
209 + auth_config_ids: t.Optional[str] = None,
210 + name: t.Optional[str] = None,
211 + order_by: t.Optional[str] = None,
212 + order_direction: t.Optional[str] = None,
213 + ) -> MCPListResponse:
214 + """
215 + List MCP servers with optional filtering and pagination.
216 +
217 + :param page_no: Page number for pagination (default: 1)
218 + :param limit: Maximum items per page (default: 10)
219 + :param toolkits: Filter by toolkit name (single string)
220 + :param auth_config_ids: Filter by auth configuration ID (single string)
221 + :param name: Filter by server name (partial match)
222 + :param order_by: Order by field ('created_at' or 'updated_at')
223 + :param order_direction: Order direction ('asc' or 'desc')
224 + :return: Paginated list of MCP servers
225 +
226 + Examples:
227 + >>> # List all servers
228 + >>> all_servers = composio.experimental.mcp.list()
229 + >>>
230 + >>> # List with pagination
231 + >>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
232 + >>>
233 + >>> # Filter by toolkit
234 + >>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
235 + """
236 +
237 + try:
238 + # Use the MCP list endpoint with filters
239 + response = self._client.mcp.list(
240 + page_no=page_no,
241 + limit=limit,
242 + toolkits=toolkits,
243 + auth_config_ids=auth_config_ids,
244 + name=name,
245 + order_by=order_by,
246 + order_direction=order_direction,
247 + )
248 +
249 + items = (
250 + response.items if hasattr(response, "items") and response.items else []
251 + )
252 +
253 + return MCPListResponse(
254 + items=items,
255 + current_page=getattr(response, "current_page", page_no or 1),
256 + total_pages=getattr(response, "total_pages", 1),
257 + )
258 +
259 + except Exception as e:
260 + raise ValidationError("Failed to list MCP servers") from e
261 +
262 + def get(self, server_id: str):
263 + """
264 + Retrieve detailed information about a specific MCP server/config.
265 +
266 + :param server_id: The unique identifier of the MCP server/config
267 + :return: Complete MCP server information
268 +
269 + Example:
270 + >>> server = composio.experimental.mcp.get('mcp_12345')
271 + >>>
272 + >>> print(server['name']) # "My Personal MCP Server"
273 + >>> print(server['allowed_tools']) # ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
274 + >>> print(server['toolkits']) # ["github", "slack"]
275 + >>> print(server['server_instance_count']) # 3
276 + """
277 + try:
278 + response = self._client.mcp.retrieve(server_id)
279 +
280 + return response
281 +
282 + except Exception as e:
283 + raise ValidationError(f"Failed to retrieve MCP server {server_id}") from e
284 +
285 + def update(
286 + self,
287 + server_id: str,
288 + name: t.Optional[str] = None,
289 + toolkits: t.Optional[t.List[t.Union[MCPToolkitConfig, str]]] = None,
290 + manually_manage_connections: t.Optional[bool] = None,
291 + allowed_tools: t.Optional[t.List[str]] = None,
292 + ):
293 + """
294 + Update an existing MCP server configuration.
295 +
296 + :param server_id: The unique identifier of the MCP server to update
297 + :param name: Optional new name for the MCP server
298 + :param toolkits: Optional list of toolkit configurations (strings or objects)
299 + :param manually_manage_connections: Optional flag for connection management
300 + :param allowed_tools: Optional list of specific tools to enable across all toolkits
301 + :return: Updated MCP server information
302 +
303 + Examples:
304 + >>> # Update server name only
305 + >>> updated_server = composio.experimental.mcp.update(
306 + ... 'mcp_12345',
307 + ... name='My Updated MCP Server'
308 + ... )
309 + >>>
310 + >>> # Update toolkits and tools
311 + >>> server_with_new_tools = composio.experimental.mcp.update(
312 + ... 'mcp_12345',
313 + ... toolkits=['github', 'slack'],
314 + ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
315 + ... )
316 + >>>
317 + >>> # Update with auth configs
318 + >>> server_with_auth = composio.experimental.mcp.update(
319 + ... 'mcp_12345',
320 + ... toolkits=[
321 + ... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
322 + ... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
323 + ... ],
324 + ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
325 + ... manually_manage_connections=False
326 + ... )
327 + """
328 + try:
329 + update_params = {}
330 +
331 + if name is not None:
332 + update_params["name"] = name
333 +
334 + if toolkits is not None:
335 + # Normalize toolkits to MCPToolkitConfig format (same as create method)
336 + normalized_toolkit_configs = []
337 + for toolkit in toolkits:
338 + if isinstance(toolkit, str):
339 + # Convert string to MCPToolkitConfig
340 + normalized_toolkit_configs.append({"toolkit": toolkit})
341 + else:
342 + # Already MCPToolkitConfig, use as-is
343 + normalized_toolkit_configs.append(toolkit)
344 +
345 + # Extract toolkits and prepare for API call
346 + toolkit_names = []
347 + auth_config_ids = []
348 +
349 + for toolkit_config in normalized_toolkit_configs:
350 + if (
351 + "toolkit" in toolkit_config
352 + and toolkit_config["toolkit"] not in toolkit_names
353 + ):
354 + toolkit_names.append(toolkit_config["toolkit"])
355 +
356 + if (
357 + "auth_config_id" in toolkit_config
358 + and toolkit_config["auth_config_id"] not in auth_config_ids
359 + ):
360 + auth_config_ids.append(toolkit_config["auth_config_id"])
361 +
362 + update_params["toolkits"] = toolkit_names
363 + update_params["auth_config_ids"] = auth_config_ids
364 +
365 + if allowed_tools is not None:
366 + update_params["custom_tools"] = allowed_tools
367 +
368 + if manually_manage_connections is not None:
369 + update_params[
370 + "managed_auth_via_composio"
371 + ] = not manually_manage_connections
372 +
373 + # Use the MCP update endpoint
374 + response = self._client.mcp.update(server_id, **update_params)
375 +
376 + return response
377 +
378 + except Exception as e:
379 + raise ValidationError(f"Failed to update MCP server {server_id}") from e
380 +
381 + def delete(self, server_id: str) -> t.Dict[str, t.Any]:
382 + """
383 + Permanently delete an MCP server configuration.
384 +
385 + :param server_id: The unique identifier of the MCP server to delete
386 + :return: Deletion result
387 +
388 + Example:
389 + >>> # Delete a server
390 + >>> result = composio.experimental.mcp.delete('mcp_12345')
391 + >>>
392 + >>> if result['deleted']:
393 + ... print(f"Server {result['id']} has been successfully deleted")
394 + >>> else:
395 + ... print(f"Failed to delete server {result['id']}")
396 + """
397 + try:
398 + response = self._client.mcp.delete(server_id)
399 +
400 + return {
401 + "id": server_id,
402 + "deleted": getattr(response, "deleted", True),
403 + }
404 +
405 + except Exception as e:
406 + raise ValidationError(f"Failed to delete MCP server {server_id}") from e
407 +
408 + def generate(
409 + self,
410 + user_id: str,
411 + mcp_config_id: str,
412 + manually_manage_connections: t.Optional[bool] = None,
413 + ) -> MCPServerInstance:
414 + """
415 + Get server URLs for an existing MCP server.
416 +
417 + This matches the TypeScript implementation exactly.
418 +
419 + :param user_id: External user ID from your database
420 + :param mcp_config_id: MCP configuration ID
421 + :param manually_manage_connections: Whether to manually manage connections (optional)
422 + :return: MCP server instance
423 +
424 + Example:
425 + >>> mcp = composio.experimental.mcp.generate(
426 + ... 'user_12345',
427 + ... 'mcp_67890',
428 + ... manually_manage_connections=False
429 + ... )
430 + >>>
431 + >>> print(mcp['url']) # Server URL for the user
432 + >>> print(mcp['allowed_tools']) # Available tools
433 + """
434 +
435 + try:
436 + # Get server details first (matching TS: this.client.mcp.retrieve)
437 + server_details = self._client.mcp.retrieve(mcp_config_id)
438 +
439 + # Generate server URLs (matching TS: this.client.mcp.generate.url)
440 + url_response = self._client.mcp.generate.url(
441 + mcp_server_id=mcp_config_id,
442 + user_ids=[user_id],
443 + managed_auth_by_composio=False if manually_manage_connections else True,
444 + )
445 +
446 + # Get the generated URL (matching TS: urlResponse.user_ids_url[0])
447 + if hasattr(url_response, "user_ids_url") and url_response.user_ids_url:
448 + server_url = url_response.user_ids_url[0]
449 + else:
450 + raise ValidationError("No server URL generated")
451 +
452 + # Create structured server instance (matching TS MCPServerInstance)
453 + server_instance: MCPServerInstance = {
454 + "id": server_details.id,
455 + "name": server_details.name,
456 + "type": "streamable_http",
457 + "url": server_url,
458 + "user_id": user_id,
459 + "allowed_tools": getattr(server_details, "allowed_tools", []),
460 + "auth_configs": getattr(server_details, "auth_config_ids", []),
461 + }
462 +
463 + return server_instance
464 +
465 + except Exception as e:
466 + if isinstance(e, ValidationError):
467 + raise
468 + raise ValidationError("Failed to parse MCP server instance") from e
python/composio/core/models/tool_router.py new
+110
@@ -0,0 +1,110 @@
1 +"""
2 +ToolRouter module for Composio SDK.
3 +
4 +This module provides tool routing session management with direct parameter usage,
5 +following Python conventions and avoiding unnecessary data transformations.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import typing as t
11 +
12 +import typing_extensions as te
13 +
14 +from composio.client import HttpClient
15 +from composio.core.models.base import Resource
16 +from composio.core.types import MCPToolkitConfig
17 +from composio.exceptions import ValidationError
18 +
19 +
20 +# Data Types
21 +
22 +
23 +class ToolRouterSession(te.TypedDict):
24 + """Tool router session response."""
25 +
26 + session_id: str # Unique session identifier
27 + url: str # Chat session MCP URL
28 +
29 +
30 +class ToolRouter(Resource):
31 + """
32 + ToolRouter class for managing tool routing sessions.
33 +
34 + Provides functionality to create sessions that route tools through
35 + the Composio platform with proper authentication and configuration.
36 + """
37 +
38 + def __init__(self, client: HttpClient):
39 + """
40 + Initialize ToolRouter instance.
41 +
42 + :param client: HTTP client for API calls
43 + """
44 + super().__init__(client)
45 +
46 + def create_session(
47 + self,
48 + user_id: str,
49 + toolkits: t.Optional[t.List[t.Union[MCPToolkitConfig, str]]] = None,
50 + manually_manage_connections: t.Optional[bool] = None,
51 + ) -> ToolRouterSession:
52 + """
53 + Create a new tool router session for a user.
54 +
55 + :param user_id: The user ID to create the session for
56 + :param toolkits: List of toolkit configurations (strings or objects)
57 + :param manually_manage_connections: Whether to manually manage connections
58 + :return: Tool router session with session_id and url
59 +
60 + Examples:
61 + >>> # Simple usage with toolkit names
62 + >>> session = composio.experimental.tool_router.create_session(
63 + ... 'user_123',
64 + ... toolkits=['github', 'slack']
65 + ... )
66 + >>>
67 + >>> # With auth configs
68 + >>> session = composio.experimental.tool_router.create_session(
69 + ... 'user_123',
70 + ... toolkits=[
71 + ... {'toolkit': 'github', 'auth_config_id': 'ac_123'},
72 + ... 'hackernews'
73 + ... ],
74 + ... manually_manage_connections=False
75 + ... )
76 + >>>
77 + >>> # Access session details
78 + >>> print(session['session_id'])
79 + >>> print(session['url'])
80 + """
81 + try:
82 + # Normalize toolkits to the format expected by the API
83 + toolkit_configs = []
84 + if toolkits:
85 + for toolkit in toolkits:
86 + if isinstance(toolkit, str):
87 + # Convert string to toolkit config
88 + toolkit_configs.append({"toolkit": toolkit})
89 + else:
90 + # Already a config object, use as-is
91 + toolkit_configs.append(toolkit)
92 +
93 + # Create session using the tool router API
94 + session = self._client.tool_router.create_session(
95 + user_id=user_id,
96 + config={
97 + "toolkits": toolkit_configs,
98 + "manually_manage_connections": manually_manage_connections,
99 + },
100 + )
101 +
102 + # Return the session response directly (no unnecessary transformations)
103 + return ToolRouterSession(
104 + session_id=session.session_id, url=session.chat_session_mcp_url
105 + )
106 +
107 + except Exception as e:
108 + raise ValidationError(
109 + f"Failed to create tool router session for user {user_id}"
110 + ) from e
python/composio/core/types.py
+12
@@ -12,9 +12,21 @@ ToolkitVersionParam = t.Union[
12 str, ToolkitVersions, None
13 ] # String can be any global version
14
15 +
16 +# Shared types for MCP and ToolRouter
17 +class MCPToolkitConfig(te.TypedDict):
18 + """Configuration for a single toolkit in MCP server or ToolRouter session."""
19 +
20 + toolkit: te.NotRequired[str] # e.g., "github", "slack", "composio_search"
21 + auth_config_id: te.NotRequired[
22 + str
23 + ] # Auth configuration ID (for toolkits requiring auth)
24 +
25 +
26 __all__ = [
27 "ToolkitLatestVersion",
28 "ToolkitVersion",
29 "ToolkitVersions",
30 "ToolkitVersionParam",
31 + "MCPToolkitConfig",
32 ]
python/composio/sdk.py
+21
@@ -15,6 +15,8 @@ from composio.core.models import (
15 Triggers,
16 )
17 from composio.core.models.base import allow_tracking
18 +from composio.core.models.mcp import MCP
19 +from composio.core.models.tool_router import ToolRouter
20 from composio.core.provider import TProvider
21 from composio.core.provider._openai import OpenAIProvider
22 from composio.core.types import ToolkitVersionParam
@@ -35,12 +37,25 @@ class SDKConfig(te.TypedDict):
37 toolkit_versions: te.NotRequired[ToolkitVersionParam]
38
39
40 +class ExperimentalNamespace:
41 + """Namespace for experimental Composio features."""
42 +
43 + def __init__(self, tool_router: ToolRouter):
44 + """
45 + Initialize experimental namespace.
46 +
47 + :param tool_router: Experimental ToolRouter instance
48 + """
49 + self.tool_router = tool_router
50 +
51 +
52 class Composio(t.Generic[TProvider], WithLogger):
53 """
54 Composio SDK for Python.
55 """
56
57 tools: Tools[TProvider]
58 + experimental: ExperimentalNamespace[TProvider]
59
60 def __init__(
61 self,
@@ -89,6 +104,12 @@ class Composio(t.Generic[TProvider], WithLogger):
104 self.triggers = Triggers(client=self._client)
105 self.auth_configs = AuthConfigs(client=self._client)
106 self.connected_accounts = ConnectedAccounts(client=self._client)
107 + self.mcp = MCP(client=self._client)
108 +
109 + # Initialize experimental features
110 + self.experimental = ExperimentalNamespace(
111 + tool_router=ToolRouter(client=self._client),
112 + )
113
114 @property
115 def client(self):
python/examples/mcp.py new
+31
@@ -0,0 +1,31 @@
1 +import asyncio
2 +from composio import Composio
3 +from langchain_mcp_adapters.client import MultiServerMCPClient
4 +from langgraph.prebuilt import create_react_agent
5 +
6 +composio = Composio()
7 +
8 +mcp_config = composio.mcp.create(
9 + name="langchain-slack-mcp",
10 + toolkits=[{"toolkit": "slack", "auth_config_id": "<auth-config-id>"}],
11 +)
12 +
13 +mcp_server = mcp_config.generate(user_id='<user-id>')
14 +
15 +client = MultiServerMCPClient(
16 + {
17 + "composio": {
18 + "url": mcp_server["url"],
19 + "transport": "streamable_http",
20 + }
21 + }
22 +)
23 +
24 +async def langchain_mcp(message: str):
25 + tools = await client.get_tools()
26 + agent = create_react_agent("openai:gpt-4.1", tools)
27 + response = await agent.ainvoke({"messages": message})
28 + return response
29 +
30 +mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))
31 +
python/providers/anthropic/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-anthropic"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your Anthropic LLMs."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/providers/anthropic/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_anthropic",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Anthropic LLMs.",
python/providers/autogen/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-autogen"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your autogen agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/autogen/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_autogen",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Autogen agent.",
python/providers/crewai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-crewai"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your CrewAI agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/crewai/setup.py
+1 -1
@@ -6,7 +6,7 @@ from setuptools import setup
6
7 setup(
8 name="composio_crewai",
9 - version="0.8.13",
9 + version="0.8.14",
10 author="Composio",
11 author_email="tech@composio.dev",
12 description="Use Composio to get an array of tools with your CrewAI agent.",
python/providers/gemini/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-gemini"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your Gemini agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/gemini/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_gemini",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Gemini agent.",
python/providers/google/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/google_adk/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-google-adk"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/google_adk/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_google_adk",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
python/providers/langchain/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langchain"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your Langchain agent."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langchain/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langchain",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your Langchain agent.",
python/providers/langgraph/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-langgraph"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get array of tools with LangGraph Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/langgraph/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_langgraph",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LangGraph Agent Workflows",
python/providers/llamaindex/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-llamaindex"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/llamaindex/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_llamaindex",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
python/providers/openai/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get an array of tools with your OpenAI Function Call."
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import setup
8
9 setup(
10 name="composio_openai",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get an array of tools with your OpenAI Function Call.",
python/providers/openai_agents/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio-openai-agents"
3 -version = "0.8.13"
3 +version = "0.8.14"
4 description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
5 readme = "README.md"
6 requires-python = ">=3.9,<4"
python/providers/openai_agents/setup.py
+1 -1
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
8
9 setup(
10 name="composio_openai_agents",
11 - version="0.8.13",
11 + version="0.8.14",
12 author="Composio",
13 author_email="tech@composio.dev",
14 description="Use Composio to get array of strongly typed tools for OpenAI Agents",
python/pyproject.toml
+1 -1
@@ -1,6 +1,6 @@
1 [project]
2 name = "composio"
3 -version = "0.8.15"
3 +version = "0.8.16"
4 description = "SDK for integrating Composio with your applications."
5 readme = "README.md"
6 requires-python = ">=3.10,<4"
python/tests/test_core_types.py
+1
@@ -56,6 +56,7 @@ class TestCoreTypes:
56 from composio.core.types import __all__
57
58 expected_exports = {
59 + "MCPToolkitConfig",
60 "ToolkitLatestVersion",
61 "ToolkitVersion",
62 "ToolkitVersions",
ts/docs/README.md
+3
@@ -43,6 +43,7 @@ The Composio SDK is built around several key concepts:
43 - **Auth Configs**: Authentication configurations for external services
44 - **Providers**: Adapters for AI services that can use tools (e.g., OpenAI)
45 - **Custom Tools**: Tools you can create and define yourself
46 +- **MCP**: Create and manage MCP Servers and clients
47
48 Check out the [Core Concepts](./core-concepts.md) documentation for more detailed information.
49
@@ -88,6 +89,8 @@ The complete API reference documentation is available here:
89 - [Auth Configs](./api/auth-configs.md)
90 - [Providers](./api/providers.md)
91 - [Custom Tools](./api/custom-tools.md)
92 +- [MCP](./api/mcp.md)
93 +- [ToolRouter (experimental)](./api/tool-router.experimental.md)
94
95 ## Providers
96
ts/docs/api/experimental-mcp.md
+566 -494
@@ -1,33 +1,27 @@
1 -# Experimental MCP (Model Control Protocol) API
1 +# MCP (Model Control Protocol) API
2
3 -The experimental MCP API provides enhanced Model Control Protocol capabilities with provider-specific optimizations and simplified configuration management. This experimental implementation builds on top of the standard MCP API, offering streamlined workflows for different AI frameworks and providers.
3 +The MCP API provides comprehensive Model Control Protocol capabilities for integrating Composio tools with modern AI frameworks. This API offers streamlined MCP server creation, management, and user-specific URL generation.
4
5 ## Overview
6
7 -The experimental MCP API introduces two key components:
7 +Key benefits of the MCP API:
8
9 -1. **`experimental.mcp`** - Enhanced MCP server operations with provider-specific response formatting
10 -2. **`experimental.mcpConfig`** - Simplified MCP configuration management
11 -
12 -Key benefits of the experimental API:
13 -- **Provider-specific optimizations**: Automatic response formatting for different AI frameworks
14 -- **Simplified configuration**: Streamlined server creation and management
15 -- **Enhanced type safety**: Better TypeScript support with provider-specific return types
16 -- **Framework integration**: Direct compatibility with popular AI frameworks like Anthropic, OpenAI, Vercel AI, Google Gemini, and Mastra
9 +- **Flexible configuration**: Support for multiple toolkits and authentication methods
10 +- **User-specific servers**: Generate unique MCP server URLs for individual users
11 +- **Comprehensive management**: Full CRUD operations for MCP server configurations
12 +- **Authentication flexibility**: Choose between manual account management or Composio-managed authentication
13
14 ## Getting Started
15
20 -### Enabling Experimental MCP
16 +### Using MCP API
17
22 -The experimental MCP features are available by default. Simply initialize Composio with your chosen provider:
18 +The MCP features are available by default when you initialize Composio:
19
20 ```typescript
21 import { Composio } from '@composio/core';
26 -import { AnthropicProvider } from '@composio/anthropic';
22
23 const composio = new Composio({
24 apiKey: process.env.COMPOSIO_API_KEY,
30 - provider: new AnthropicProvider(),
25 });
26 ```
27
@@ -35,466 +29,401 @@ const composio = new Composio({
29
30 ```typescript
31 // 1. Create MCP configuration
38 -const mcpConfig = await composio.experimental.mcpConfig.create(
39 - "my-server-name",
40 - [
41 - {
42 - authConfigId: "ac_your_auth_config",
43 - allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
44 - }
45 - ],
46 - { isChatAuth: true }
47 -);
32 +const mcpConfig = await composio.mcp.create('my-server-name', {
33 + toolkits: [{ toolkit: 'github', authConfigId: 'ac_233434343' }],
34 + allowedTools: ['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS'],
35 + manuallyManageConnections: false,
36 +});
37
49 -// 2. Get server URLs for a user
50 -const servers = await composio.experimental.mcp.getServer(
51 - "user123",
52 - mcpConfig.id,
53 - { limitTools: ["GMAIL_FETCH_EMAILS"] }
54 -);
38 +// 2. Generate server instance for a user
39 +const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
40
56 -// 3. Use with your AI framework (provider-specific format)
57 -// servers is automatically formatted for your chosen provider
41 +// 3. Use the server URL with any MCP client
42 +const mcpUrl = serverInstance.url;
43 ```
44
45 ## API Reference
46
62 -### experimental.mcpConfig
63 -
64 -The `mcpConfig` class provides simplified MCP server configuration management.
47 +### composio.mcp
48
66 -#### create(name, serverConfig, options)
49 +#### create(name, mcpConfig)
50
51 Creates a new MCP server configuration with the specified toolkit settings.
52
53 ```typescript
71 -const mcpConfig = await composio.experimental.mcpConfig.create(
72 - "gmail-assistant",
73 - [
74 - {
75 - authConfigId: "ac_gmail_config",
76 - allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
77 - },
78 - {
79 - authConfigId: "ac_slack_config",
80 - allowedTools: ["SLACK_SEND_MESSAGE"]
81 - }
54 +const mcpConfig = await composio.mcp.create('gmail-assistant', {
55 + toolkits: [
56 + { toolkit: 'gmail', authConfigId: 'ac_gmail_config' },
57 + { toolkit: 'slack', authConfigId: 'ac_slack_config' },
58 ],
83 - {
84 - isChatAuth: true // Use Composio-managed authentication
85 - }
86 -);
59 + allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'SLACK_SEND_MESSAGE'],
60 + manuallyManageConnections: false,
61 +});
62 +
63 +// Alternative with string toolkit names
64 +const mcpConfig = await composio.mcp.create('simple-server', {
65 + toolkits: ['github', 'slack'],
66 + allowedTools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
67 + manuallyManageConnections: false,
68 +});
69 ```
70
71 **Parameters:**
72
73 - `name` (string): Unique name for the MCP server configuration
92 -- `serverConfig` (Array): Array of authentication and tool configurations
93 - - `authConfigId`: The authentication configuration ID to use
94 - - `allowedTools`: Array of specific tool IDs to expose through this configuration
95 -- `options` (object): Configuration options
96 - - `isChatAuth` (boolean, optional): Whether to use Composio-managed authentication
74 +- `mcpConfig` (object): MCP configuration parameters
75 + - `toolkits` (Array): Array of toolkit configurations - can be strings or objects
76 + - As string: Just the toolkit name (e.g., "github", "slack")
77 + - As object: `{ toolkit?: string, authConfigId?: string }`
78 + - `allowedTools` (string[], optional): Array of specific tool IDs to expose
79 + - `manuallyManageConnections` (boolean, optional): Whether to manually manage account connections. If false, Composio will inject account management tools. Defaults to false.
80 +
81 +**Returns:** `Promise<MCPConfigCreateResponse>` - Created server details including:
82
98 -**Returns:** `Promise<McpServerCreateResponse>` - Created server details including:
83 - `id`: Server configuration UUID
84 - `name`: Server name
101 -- `toolkits`: Array of toolkit names
102 -- `getServer`: Convenience method to get server URLs
103 -
104 -#### getByName(configName)
105 -
106 -Retrieves an existing MCP configuration by its name.
107 -
108 -```typescript
109 -const existingConfig = await composio.experimental.mcpConfig.getByName('gmail-assistant');
110 -```
85 +- `allowedTools`: Array of allowed tool IDs
86 +- `authConfigIds`: Array of auth configuration IDs
87 +- `commands`: Setup commands for different MCP clients (Claude, Cursor, Windsurf)
88 +- `MCPUrl`: Base MCP server URL
89 +- `generate`: Convenience method to generate user-specific server instances
90
112 -**Parameters:**
113 -- `configName` (string): Name of the MCP configuration to retrieve
114 -
115 -**Returns:** `Promise<McpRetrieveResponse>` - Configuration details
116 -
117 -### experimental.mcp
118 -
119 -The experimental MCP class provides enhanced server operations with provider-specific response formatting.
120 -
121 -#### getServer(userId, mcpConfigurationId, options?)
91 +#### generate(userId, mcpConfigurationId, options?)
92
123 -Retrieves MCP server URLs formatted specifically for your chosen provider.
93 +Generates a user-specific MCP server instance with a unique URL.
94
95 ```typescript
126 -// Returns provider-specific format
127 -const servers = await composio.experimental.mcp.getServer(
128 - "user123",
129 - "mcp_config_uuid",
130 - {
131 - limitTools: ["GMAIL_FETCH_EMAILS"],
132 - isChatAuth: true
133 - }
134 -);
96 +const serverInstance = await composio.mcp.generate('user123', 'mcp_config_uuid', {
97 + manuallyManageConnections: false,
98 +});
99 ```
100
101 **Parameters:**
102
139 -- `userId` (string): ID of the user to generate server URLs for
103 +- `userId` (string): ID of the user to generate server instance for
104 - `mcpConfigurationId` (string): UUID of the MCP configuration
105 - `options` (object, optional): Additional server options
142 - - `limitTools` (string[]): Subset of tools to expose (from the configuration)
143 - - `isChatAuth` (boolean): Override authentication method
106 + - `manuallyManageConnections` (boolean): Override authentication method
107
145 -**Returns:** Provider-specific response format (see [Provider Integration](#provider-integration))
108 +**Returns:** `Promise<MCPServerInstance>` - Server instance details including:
109
147 -#### getRawMCPServer(userId, mcpConfigurationId, options?)
148 -
149 -Returns the raw MCP server response without provider-specific formatting.
150 -
151 -```typescript
152 -const rawServer = await composio.experimental.mcp.getRawMCPServer(
153 - "user123",
154 - "mcp_config_uuid"
155 -);
156 -```
157 -
158 -**Parameters:** Same as `getServer()`
159 -
160 -**Returns:** Raw MCP server response
161 -
162 -## Provider Integration
163 -
164 -The experimental MCP API automatically formats responses based on your chosen provider:
110 +- `id`: Server configuration ID
111 +- `name`: Server name
112 +- `type`: Connection type (always 'streamable_http')
113 +- `url`: User-specific MCP server URL
114 +- `userId`: Associated user ID
115 +- `allowedTools`: Array of available tool IDs
116 +- `authConfigs`: Array of auth configuration IDs
117
166 -### Anthropic Provider
118 +#### list(options)
119
168 -Returns an array of server configurations compatible with Anthropic's MCP client:
120 +Lists MCP server configurations with optional filtering and pagination.
121
122 ```typescript
171 -import { AnthropicProvider } from '@composio/anthropic';
123 +// List all MCP servers
124 +const allServers = await composio.mcp.list({});
125
173 -const composio = new Composio({
174 - provider: new AnthropicProvider(),
126 +// List with pagination
127 +const pagedServers = await composio.mcp.list({
128 + page: 2,
129 + limit: 5
130 });
131
177 -const servers = await composio.experimental.mcp.getServer(userId, configId);
178 -// Returns: McpServerUrlInfo[]
179 -// [
180 -// {
181 -// url: new URL("https://mcp.composio.dev/..."),
182 -// name: "gmail-assistant-user123",
183 -// toolkit: "gmail"
184 -// }
185 -// ]
132 +// Filter by toolkit
133 +const githubServers = await composio.mcp.list({
134 + toolkits: ['github', 'slack']
135 +});
136
187 -// Use with Anthropic Claude
188 -const stream = anthropic.beta.messages.stream({
189 - model: 'claude-4-sonnet-20250514',
190 - mcp_servers: servers,
191 - messages: [...],
192 - betas: ['mcp-client-2025-04-04'],
137 +// Filter by name
138 +const namedServers = await composio.mcp.list({
139 + name: 'personal'
140 });
141 ```
142
196 -### Google Gemini Provider
143 +**Parameters:**
144
198 -Returns a URL string for use with Google's MCP integration:
145 +- `options` (object): Filtering and pagination options
146 + - `page` (number, optional): Page number for pagination (1-based, defaults to 1)
147 + - `limit` (number, optional): Maximum items per page (defaults to 10)
148 + - `toolkits` (string[], optional): Filter by toolkit names
149 + - `authConfigs` (string[], optional): Filter by auth configuration IDs
150 + - `name` (string, optional): Filter by server name (partial match)
151
200 -```typescript
201 -import { GoogleProvider } from '@composio/google';
202 -import { GoogleGenAI, mcpToTool } from '@google/genai';
152 +**Returns:** `Promise<MCPListResponse>` - Paginated list with metadata:
153
204 -const composio = new Composio({
205 - provider: new GoogleProvider(),
206 -});
154 +- `items`: Array of MCP server configurations
155 +- `currentPage`: Current page number
156 +- `totalPages`: Total number of pages
157
208 -const url = await composio.experimental.mcp.getServer(userId, configId);
209 -// Returns: string (URL)
158 +#### get(serverId)
159
211 -// Create MCP client and tools
212 -const serverParams = new SSEClientTransport(url);
213 -const mcpClient = new MCPClient({
214 - name: 'composio-mcp-client',
215 - version: '1.0.0',
216 -});
160 +Retrieves detailed information about a specific MCP server.
161
218 -await mcpClient.connect(serverParams);
219 -const tools = [mcpToTool(mcpClient)];
162 +```typescript
163 +const server = await composio.mcp.get("mcp_12345");
164
221 -// Use with Google Gemini
222 -const gemini = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
223 -const stream = await gemini.models.generateContentStream({
224 - model: 'gemini-2.5-flash',
225 - contents: 'Your prompt here',
226 - config: { tools },
227 -});
165 +console.log(server.name); // "My Personal MCP Server"
166 +console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
167 +console.log(server.toolkits); // ["github", "slack"]
168 +console.log(server.serverInstanceCount); // 3
169 +
170 +// Access setup commands for different clients
171 +console.log(server.commands.claude); // Claude setup command
172 +console.log(server.commands.cursor); // Cursor setup command
173 +console.log(server.commands.windsurf); // Windsurf setup command
174 ```
175
230 -### Mastra Provider
176 +**Parameters:**
177
232 -Returns a key-value mapping of server configurations:
178 +- `serverId` (string): The unique identifier of the MCP server
179
234 -```typescript
235 -import { MastraProvider } from '@composio/mastra';
236 -import { MCPClient as MastraMCPClient } from '@mastra/mcp';
180 +**Returns:** `Promise<MCPItem>` - Complete server details including configuration, tools, and metadata
181
238 -const composio = new Composio({
239 - provider: new MastraProvider(),
240 -});
182 +#### update(serverId, config)
183
242 -const servers = await composio.experimental.mcp.getServer(userId, configId);
243 -// Returns: Record<string, { url: string }>
244 -// {
245 -// "server-0": { url: "https://mcp.composio.dev/..." }
246 -// }
184 +Updates an existing MCP server configuration.
185
248 -// Use with Mastra
249 -const mcpClient = new MastraMCPClient({ servers });
250 -const tools = await mcpClient.getTools();
186 +```typescript
187 +// Update server name only
188 +const updatedServer = await composio.mcp.update("mcp_12345", {
189 + name: "My Updated MCP Server"
190 +});
191
252 -const agent = new MastraAgent({
253 - name: 'Gmail Assistant',
254 - model: openai('gpt-4o-mini'),
255 - tools: wrapTools(servers, tools),
192 +// Update toolkits and tools
193 +const serverWithNewTools = await composio.mcp.update("mcp_12345", {
194 + toolkits: [
195 + {
196 + toolkit: "github",
197 + authConfigId: "auth_abc123"
198 + },
199 + {
200 + toolkit: "slack",
201 + authConfigId: "auth_xyz789"
202 + }
203 + ],
204 + allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS", "SLACK_SEND_MESSAGE"]
205 });
206 ```
207
259 -### Vercel AI Provider
208 +**Parameters:**
209
261 -Returns a URL string for use with Vercel AI's MCP client:
210 +- `serverId` (string): The unique identifier of the MCP server to update
211 +- `config` (object): Update configuration parameters
212 + - `name` (string, optional): New name for the MCP server
213 + - `toolkits` (Array, optional): Updated toolkit configurations
214 + - `allowedTools` (string[], optional): Updated list of allowed tools
215 + - `manuallyManageConnections` (boolean, optional): Updated connection management setting
216
263 -```typescript
264 -import { VercelProvider } from '@composio/vercel';
265 -import { experimental_createMCPClient as createMCPClient, streamText } from 'ai';
217 +**Returns:** `Promise<MCPItem>` - Updated MCP server configuration
218
267 -const composio = new Composio({
268 - provider: new VercelProvider(),
269 -});
270 -
271 -const url = await composio.experimental.mcp.getServer(userId, configId);
272 -// Returns: string (URL)
219 +#### delete(serverId)
220
274 -// Create Vercel AI MCP client
275 -const serverParams = new SSEClientTransport(url);
276 -const mcpClient = await createMCPClient({
277 - name: 'composio-mcp-client',
278 - transport: serverParams,
279 -});
221 +Permanently deletes an MCP server configuration.
222
281 -const tools = await mcpClient.tools();
223 +```typescript
224 +const result = await composio.mcp.delete("mcp_12345");
225
283 -// Use with Vercel AI
284 -const stream = streamText({
285 - model: openai('gpt-4o-mini'),
286 - messages: [...],
287 - tools,
288 -});
226 +if (result.deleted) {
227 + console.log(`Server ${result.id} has been successfully deleted`);
228 +}
229 ```
230
291 -### OpenAI Provider
292 -
293 -Returns an array of server configurations:
231 +**Parameters:**
232
295 -```typescript
296 -import { OpenAIProvider } from '@composio/openai';
233 +- `serverId` (string): The unique identifier of the MCP server to delete
234
298 -const composio = new Composio({
299 - provider: new OpenAIProvider(),
300 -});
235 +**Returns:** `Promise<{id: string; deleted: boolean}>` - Deletion confirmation
236
302 -const servers = await composio.experimental.mcp.getServer(userId, configId);
303 -// Returns: McpServerUrlInfo[]
304 -```
237 +**⚠️ Warning:** This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
238
239 ## Complete Examples
240
308 -### Anthropic Claude Example
241 +### Basic MCP Server Setup
242
243 ```typescript
244 import { Composio } from '@composio/core';
312 -import { AnthropicProvider } from '@composio/anthropic';
313 -import Anthropic from '@anthropic-ai/sdk';
245
315 -// 1. Initialize Composio with experimental MCP
246 +// 1. Initialize Composio
247 const composio = new Composio({
248 apiKey: process.env.COMPOSIO_API_KEY,
318 - provider: new AnthropicProvider({ cacheTools: true }),
249 });
250
251 // 2. Create MCP configuration
322 -const mcpConfig = await composio.experimental.mcpConfig.create(
323 - `gmail-assistant-${Date.now()}`,
324 - [
325 - {
326 - authConfigId: "ac_your_gmail_config",
327 - allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
328 - }
329 - ],
330 - { isChatAuth: true }
331 -);
332 -
333 -// 3. Get server URLs for connected account
334 -const servers = await composio.experimental.mcp.getServer(
335 - "user123",
336 - mcpConfig.id,
337 - { limitTools: ["GMAIL_FETCH_EMAILS"] }
338 -);
339 -
340 -// 4. Use with Anthropic Claude
341 -const anthropic = new Anthropic({
342 - apiKey: process.env.ANTHROPIC_API_KEY,
252 +const mcpConfig = await composio.mcp.create('gmail-assistant', {
253 + toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_your_gmail_config' }],
254 + allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
255 + manuallyManageConnections: false,
256 });
257
345 -const stream = anthropic.beta.messages.stream({
346 - model: 'claude-4-sonnet-20250514',
347 - max_tokens: 64_000,
348 - mcp_servers: servers,
349 - messages: [
350 - {
351 - role: 'user',
352 - content: 'Fetch my latest 3 emails and summarize them',
353 - },
354 - ],
355 - betas: ['mcp-client-2025-04-04'],
356 -});
258 +console.log('MCP Configuration created:', mcpConfig.id);
259 +console.log('Setup commands:');
260 +console.log('Claude:', mcpConfig.commands.claude);
261 +console.log('Cursor:', mcpConfig.commands.cursor);
262 +console.log('Windsurf:', mcpConfig.commands.windsurf);
263
358 -for await (const event of stream) {
359 - if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
360 - process.stdout.write(event.delta.text);
361 - }
362 -}
264 +// 3. Generate server instance for a user
265 +const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
266 +
267 +console.log('MCP Server URL for user123:', serverInstance.url);
268 +console.log('Available tools:', serverInstance.allowedTools);
269 ```
270
365 -### Google Gemini Example
271 +### Using with Generic MCP Client
272
273 ```typescript
274 import { Composio } from '@composio/core';
369 -import { GoogleProvider } from '@composio/google';
370 -import { GoogleGenAI, mcpToTool } from '@google/genai';
275 import { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';
276 import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
277
374 -// 1. Initialize Composio
278 +// 1. Initialize Composio and create MCP configuration
279 const composio = new Composio({
280 apiKey: process.env.COMPOSIO_API_KEY,
377 - provider: new GoogleProvider(),
281 });
282
380 -// 2. Create MCP configuration
381 -const mcpConfig = await composio.experimental.mcpConfig.create(
382 - `gmail-assistant-${Date.now()}`,
383 - [
384 - {
385 - authConfigId: "ac_your_gmail_config",
386 - allowedTools: ["GMAIL_FETCH_EMAILS"]
387 - }
283 +const mcpConfig = await composio.mcp.create('multi-toolkit-assistant', {
284 + toolkits: [
285 + { toolkit: 'gmail', authConfigId: 'ac_gmail_config' },
286 + { toolkit: 'github', authConfigId: 'ac_github_config' },
287 ],
389 - { isChatAuth: true }
390 -);
288 + allowedTools: [
289 + 'GMAIL_FETCH_EMAILS',
290 + 'GMAIL_SEND_EMAIL',
291 + 'GITHUB_CREATE_ISSUE',
292 + 'GITHUB_LIST_REPOS'
293 + ],
294 + manuallyManageConnections: false,
295 +});
296
392 -// 3. Get server URL
393 -const url = await composio.experimental.mcp.getServer(
394 - "user123",
395 - mcpConfig.id
396 -);
297 +// 2. Generate server instance for a specific user
298 +const serverInstance = await composio.mcp.generate('user456', mcpConfig.id);
299
398 -// 4. Create MCP client
399 -const serverParams = new SSEClientTransport(url);
300 +// 3. Create MCP client connection
301 +const transport = new SSEClientTransport(new URL(serverInstance.url));
302 const mcpClient = new MCPClient({
303 name: 'composio-mcp-client',
304 version: '1.0.0',
305 });
306
405 -await mcpClient.connect(serverParams);
406 -const tools = [mcpToTool(mcpClient)];
307 +await mcpClient.connect(transport);
308
408 -// 5. Use with Google Gemini
409 -const gemini = new GoogleGenAI({
410 - apiKey: process.env.GEMINI_API_KEY,
411 -});
309 +// 4. List available tools
310 +const { tools } = await mcpClient.listTools();
311 +console.log('Available tools:', tools.map(t => t.name));
312
413 -const stream = await gemini.models.generateContentStream({
414 - model: 'gemini-2.5-flash',
415 - contents: 'Fetch my latest 2 emails and provide a summary',
416 - config: { tools },
313 +// 5. Call a tool
314 +const result = await mcpClient.callTool({
315 + name: 'GMAIL_FETCH_EMAILS',
316 + arguments: {
317 + limit: 5
318 + }
319 });
320
419 -for await (const chunk of stream) {
420 - console.log(chunk.text);
421 -}
321 +console.log('Email fetch result:', result);
322
323 +// 6. Clean up
324 await mcpClient.close();
325 ```
326
426 -### Mastra Example
327 +### Managing Multiple Servers
328
329 ```typescript
429 -import { openai } from '@ai-sdk/openai';
330 import { Composio } from '@composio/core';
431 -import { MastraProvider } from '@composio/mastra';
432 -import { MCPClient as MastraMCPClient } from '@mastra/mcp';
433 -import { Agent as MastraAgent } from '@mastra/core/agent';
331
435 -// Helper function to remove server prefixes from tool names
436 -function wrapTools(servers: Record<string, any>, tools: Record<string, any>): Record<string, any> {
437 - const prefixes = Object.keys(servers);
438 -
439 - function removePrefix(str: string): string {
440 - for (const prefix of prefixes) {
441 - if (str.startsWith(prefix)) {
442 - return str.slice(prefix.length + 1);
443 - }
444 - }
445 - return str;
446 - }
447 -
448 - return Object.fromEntries(
449 - Object.entries(tools).map(([key, tool]) => {
450 - return [removePrefix(key), tool] as const;
451 - })
452 - );
453 -}
454 -
455 -// 1. Initialize Composio
332 const composio = new Composio({
333 apiKey: process.env.COMPOSIO_API_KEY,
458 - provider: new MastraProvider(),
334 });
335
461 -// 2. Create MCP configuration
462 -const mcpConfig = await composio.experimental.mcpConfig.create(
463 - `gmail-assistant-${Date.now()}`,
464 - [
465 - {
466 - authConfigId: "ac_your_gmail_config",
467 - allowedTools: ["GMAIL_FETCH_EMAILS"]
468 - }
336 +// Create multiple MCP configurations for different use cases
337 +const personalConfig = await composio.mcp.create('personal-assistant', {
338 + toolkits: ['gmail', 'calendar'],
339 + allowedTools: ['GMAIL_FETCH_EMAILS', 'CALENDAR_LIST_EVENTS'],
340 + manuallyManageConnections: false,
341 +});
342 +
343 +const workConfig = await composio.mcp.create('work-assistant', {
344 + toolkits: [
345 + { toolkit: 'github', authConfigId: 'ac_work_github' },
346 + { toolkit: 'slack', authConfigId: 'ac_work_slack' },
347 ],
470 - { isChatAuth: true }
471 -);
348 + allowedTools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
349 + manuallyManageConnections: false,
350 +});
351
473 -// 3. Get server URLs
474 -const servers = await composio.experimental.mcp.getServer(
475 - "user123",
476 - mcpConfig.id
477 -);
352 +// List all configurations
353 +const allConfigs = await composio.mcp.list({});
354 +console.log(`Total configurations: ${allConfigs.items.length}`);
355 +
356 +// Generate instances for different users
357 +const personalInstance = await composio.mcp.generate('user123', personalConfig.id);
358 +const workInstance = await composio.mcp.generate('user123', workConfig.id);
359 +
360 +console.log('Personal MCP URL:', personalInstance.url);
361 +console.log('Work MCP URL:', workInstance.url);
362 +
363 +// Update a configuration
364 +const updatedConfig = await composio.mcp.update(personalConfig.id, {
365 + name: 'Enhanced Personal Assistant',
366 + allowedTools: [
367 + 'GMAIL_FETCH_EMAILS',
368 + 'GMAIL_SEND_EMAIL',
369 + 'CALENDAR_LIST_EVENTS',
370 + 'CALENDAR_CREATE_EVENT'
371 + ]
372 +});
373 +
374 +console.log('Updated configuration:', updatedConfig.name);
375 +```
376 +
377 +### Vercel AI Integration Example
378 +
379 +```typescript
380 +import { Composio } from '@composio/core';
381 +import { experimental_createMCPClient as createMCPClient, streamText } from 'ai';
382 +import { openai } from '@ai-sdk/openai';
383 +import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
384 +
385 +// 1. Initialize Composio and create MCP configuration
386 +const composio = new Composio({
387 + apiKey: process.env.COMPOSIO_API_KEY,
388 +});
389 +
390 +const mcpConfig = await composio.mcp.create('ai-assistant', {
391 + toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_gmail_config' }],
392 + allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
393 + manuallyManageConnections: false,
394 +});
395
479 -// 4. Create Mastra MCP client
480 -const mcpClient = new MastraMCPClient({ servers });
481 -const tools = await mcpClient.getTools();
396 +// 2. Generate server instance
397 +const serverInstance = await composio.mcp.generate('user789', mcpConfig.id);
398
483 -// 5. Create Mastra agent
484 -const agent = new MastraAgent({
485 - name: 'Gmail Assistant',
486 - instructions: 'You are a helpful Gmail assistant.',
399 +// 3. Create Vercel AI MCP client
400 +const transport = new SSEClientTransport(new URL(serverInstance.url));
401 +const mcpClient = await createMCPClient({
402 + name: 'composio-mcp-client',
403 + transport: transport,
404 +});
405 +
406 +const tools = await mcpClient.tools();
407 +
408 +// 4. Use with Vercel AI
409 +const stream = streamText({
410 model: openai('gpt-4o-mini'),
488 - tools: wrapTools(servers, tools),
411 + messages: [
412 + {
413 + role: 'user',
414 + content: 'Fetch my latest 3 emails and provide a summary of each one',
415 + },
416 + ],
417 + tools,
418 });
419
491 -// 6. Use the agent
492 -const response = await agent.generate(
493 - 'Fetch my latest 2 emails and provide a summary'
494 -);
495 -console.log(response.text);
420 +// 5. Stream the response
421 +for await (const textPart of stream.textStream) {
422 + process.stdout.write(textPart);
423 +}
424
497 -await mcpClient.disconnect();
425 +// 6. Clean up
426 +await mcpClient.close();
427 ```
428
429 ## Configuration Management
@@ -512,16 +441,11 @@ const authConfig = await composio.authConfigs.create({
441 });
442
443 // Use the auth config ID in your MCP configuration
515 -const mcpConfig = await composio.experimental.mcpConfig.create(
516 - "gmail-server",
517 - [
518 - {
519 - authConfigId: authConfig.id,
520 - allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
521 - }
522 - ],
523 - { isChatAuth: true }
524 -);
444 +const mcpConfig = await composio.mcp.create('gmail-server', {
445 + toolkits: [{ toolkit: 'gmail', authConfigId: authConfig.id }],
446 + allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
447 + manuallyManageConnections: false,
448 +});
449 ```
450
451 ### Tool Selection
@@ -529,98 +453,153 @@ const mcpConfig = await composio.experimental.mcpConfig.create(
453 You can specify exactly which tools to expose through your MCP server:
454
455 ```typescript
532 -const mcpConfig = await composio.experimental.mcpConfig.create(
533 - "multi-toolkit-server",
534 - [
535 - {
536 - authConfigId: "ac_gmail_config",
537 - allowedTools: [
538 - "GMAIL_FETCH_EMAILS",
539 - "GMAIL_SEND_EMAIL",
540 - "GMAIL_CREATE_DRAFT"
541 - ]
542 - },
543 - {
544 - authConfigId: "ac_slack_config",
545 - allowedTools: [
546 - "SLACK_SEND_MESSAGE",
547 - "SLACK_LIST_CHANNELS"
548 - ]
549 - }
456 +const mcpConfig = await composio.mcp.create('multi-toolkit-server', {
457 + toolkits: [
458 + { toolkit: 'gmail', authConfigId: 'ac_gmail_config' },
459 + { toolkit: 'slack', authConfigId: 'ac_slack_config' },
460 ],
551 - { isChatAuth: true }
552 -);
461 + allowedTools: [
462 + 'GMAIL_FETCH_EMAILS',
463 + 'GMAIL_SEND_EMAIL',
464 + 'GMAIL_CREATE_DRAFT',
465 + 'SLACK_SEND_MESSAGE',
466 + 'SLACK_LIST_CHANNELS',
467 + ],
468 + manuallyManageConnections: false,
469 +});
470 ```
471
555 -### Runtime Tool Limiting
472 +### Flexible Toolkit Configuration
473
557 -You can further limit tools when getting server URLs:
474 +You can configure toolkits in multiple ways:
475
476 ```typescript
560 -const servers = await composio.experimental.mcp.getServer(
561 - "user123",
562 - mcpConfig.id,
563 - {
564 - limitTools: ["GMAIL_FETCH_EMAILS"], // Only expose this tool
565 - isChatAuth: true
566 - }
567 -);
477 +// Using string array (requires default auth configs)
478 +const simpleConfig = await composio.mcp.create('simple-server', {
479 + toolkits: ['github', 'slack'],
480 + allowedTools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
481 + manuallyManageConnections: false,
482 +});
483 +
484 +// Using mixed configuration
485 +const mixedConfig = await composio.mcp.create('mixed-server', {
486 + toolkits: [
487 + 'calendar', // Uses default auth config
488 + { toolkit: 'gmail', authConfigId: 'ac_specific_gmail' }, // Uses specific auth config
489 + { authConfigId: 'ac_custom_integration' }, // Uses auth config without toolkit name
490 + ],
491 + manuallyManageConnections: false,
492 +});
493 ```
494
495 ## Types
496
572 -### MCPServerConfig
497 +### MCPConfigCreationParams
498
499 ```typescript
575 -interface MCPServerConfig {
576 - authConfigId: string; // Authentication configuration ID
577 - allowedTools: string[]; // Array of tool IDs to expose
500 +interface MCPConfigCreationParams {
501 + toolkits: Array<string | MCPConfigToolkits>; // Array of toolkit configurations
502 + allowedTools?: string[]; // Optional array of specific tool IDs to expose
503 + manuallyManageConnections?: boolean; // Whether to manually manage account connections (default: false)
504 +}
505 +
506 +interface MCPConfigToolkits {
507 + toolkit?: string; // Toolkit identifier (e.g., "github", "slack")
508 + authConfigId?: string; // Authentication configuration ID
509 }
510 ```
511
581 -### MCPConfigOptions
512 +### MCPConfigCreateResponse
513
514 ```typescript
584 -interface MCPConfigOptions {
585 - isChatAuth?: boolean; // Use Composio-managed authentication
515 +interface MCPConfigCreateResponse {
516 + id: string; // Configuration UUID
517 + name: string; // Configuration name
518 + allowedTools: string[]; // Array of allowed tool IDs
519 + authConfigIds: string[]; // Array of auth configuration IDs
520 + commands: {
521 + claude: string; // Claude setup command
522 + cursor: string; // Cursor setup command
523 + windsurf: string; // Windsurf setup command
524 + };
525 + MCPUrl: string; // Base MCP server URL
526 + generate: (userId: string) => Promise<MCPServerInstance>; // Convenience method
527 }
528 ```
529
589 -### McpServerCreateResponse
530 +### MCPServerInstance
531
532 ```typescript
592 -interface McpServerCreateResponse<T> {
593 - id: string; // Configuration UUID
594 - name: string; // Configuration name
595 - toolkits: string[]; // Array of toolkit names
596 - createdAt?: string; // Creation timestamp
597 - updatedAt?: string; // Last update timestamp
598 - getServer: (params: { // Convenience method
599 - userId?: string;
600 - limitTools?: string[];
601 - isChatAuth?: boolean;
602 - }) => Promise<T>;
533 +interface MCPServerInstance {
534 + id: string; // Server configuration ID
535 + name: string; // Server name
536 + type: 'streamable_http'; // Connection type
537 + url: string; // User-specific MCP server URL
538 + userId: string; // Associated user ID
539 + allowedTools: string[]; // Array of available tool IDs
540 + authConfigs: string[]; // Array of auth configuration IDs
541 }
542 ```
543
606 -### Provider-Specific Response Types
544 +### MCPListParams
545 +
546 +```typescript
547 +interface MCPListParams {
548 + page?: number; // Page number for pagination (1-based, default: 1)
549 + limit?: number; // Maximum items per page (default: 10)
550 + toolkits?: string[]; // Filter by toolkit names
551 + authConfigs?: string[]; // Filter by auth configuration IDs
552 + name?: string; // Filter by server name (partial match)
553 +}
554 +```
555
608 -#### McpServerUrlInfo (Anthropic, OpenAI, etc.)
556 +### MCPListResponse
557
558 ```typescript
611 -interface McpServerUrlInfo {
612 - url: URL; // MCP server URL
613 - name: string; // Server instance name
614 - toolkit?: string; // Associated toolkit
559 +interface MCPListResponse {
560 + items: MCPItem[]; // Array of MCP server configurations
561 + currentPage: number; // Current page number
562 + totalPages: number; // Total number of pages
563 }
564 ```
565
618 -#### Mastra Server Format
566 +### MCPItem
567
568 ```typescript
621 -type MastraServerFormat = Record<string, {
622 - url: string; // MCP server URL
623 -}>;
569 +interface MCPItem {
570 + id: string; // Server configuration ID
571 + name: string; // Server name
572 + allowedTools: string[]; // Array of allowed tool IDs
573 + authConfigIds: string[]; // Array of auth configuration IDs
574 + commands: {
575 + claude: string; // Claude setup command
576 + cursor: string; // Cursor setup command
577 + windsurf: string; // Windsurf setup command
578 + };
579 + MCPUrl: string; // Base MCP server URL
580 + toolkitIcons: Record<string, string>; // Toolkit icons mapping
581 + serverInstanceCount: number; // Number of active server instances
582 + toolkits: string[]; // Array of associated toolkit names
583 +}
584 +```
585 +
586 +### MCPUpdateParams
587 +
588 +```typescript
589 +interface MCPUpdateParams {
590 + name?: string; // Updated server name
591 + toolkits?: Array<string | MCPConfigToolkits>; // Updated toolkit configurations
592 + allowedTools?: string[]; // Updated array of allowed tools
593 + manuallyManageConnections?: boolean; // Updated connection management setting
594 +}
595 +```
596 +
597 +### MCPGetInstanceParams
598 +
599 +```typescript
600 +interface MCPGetInstanceParams {
601 + manuallyManageConnections?: boolean; // Whether to manually manage account connections (default: false)
602 +}
603 ```
604
605 ## Best Practices
@@ -631,17 +610,21 @@ Use descriptive names that indicate the purpose and scope:
610
611 ```typescript
612 // Good
634 -await composio.experimental.mcpConfig.create(
613 +await composio.mcp.create(
614 "gmail-support-assistant",
636 - [...],
637 - { isChatAuth: true }
615 + {
616 + toolkits: [...],
617 + manuallyManageConnections: false
618 + }
619 );
620
621 // Avoid
641 -await composio.experimental.mcpConfig.create(
622 +await composio.mcp.create(
623 "config1",
643 - [...],
644 - { isChatAuth: true }
624 + {
625 + toolkits: [...],
626 + manuallyManageConnections: false
627 + }
628 );
629 ```
630
@@ -651,32 +634,18 @@ Be specific about which tools to expose:
634
635 ```typescript
636 // Good - specific tools for the use case
654 -const mcpConfig = await composio.experimental.mcpConfig.create(
655 - "email-assistant",
656 - [
657 - {
658 - authConfigId: "ac_gmail",
659 - allowedTools: [
660 - "GMAIL_FETCH_EMAILS",
661 - "GMAIL_SEND_EMAIL",
662 - "GMAIL_CREATE_DRAFT"
663 - ]
664 - }
665 - ],
666 - { isChatAuth: true }
667 -);
637 +const mcpConfig = await composio.mcp.create('email-assistant', {
638 + toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_gmail' }],
639 + allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
640 + manuallyManageConnections: false,
641 +});
642
643 // Avoid - exposing unnecessary tools
670 -const mcpConfig = await composio.experimental.mcpConfig.create(
671 - "email-assistant",
672 - [
673 - {
674 - authConfigId: "ac_gmail",
675 - allowedTools: ["*"] // Exposes all tools
676 - }
677 - ],
678 - { isChatAuth: true }
679 -);
644 +const mcpConfig = await composio.mcp.create('email-assistant', {
645 + toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_gmail' }],
646 + // No allowedTools specified - exposes all tools
647 + manuallyManageConnections: false,
648 +});
649 ```
650
651 ### 3. Authentication Management
@@ -685,10 +654,12 @@ Use Composio-managed authentication when possible:
654
655 ```typescript
656 // Recommended
688 -const mcpConfig = await composio.experimental.mcpConfig.create(
657 +const mcpConfig = await composio.mcp.create(
658 "server-name",
690 - [...],
691 - { isChatAuth: true } // Let Composio handle auth
659 + {
660 + toolkits: [...],
661 + manuallyManageConnections: false // Let Composio handle auth
662 + }
663 );
664 ```
665
@@ -698,18 +669,14 @@ Always handle potential errors:
669
670 ```typescript
671 try {
701 - const mcpConfig = await composio.experimental.mcpConfig.create(
702 - "server-name",
703 - serverConfigs,
704 - { isChatAuth: true }
705 - );
706 -
707 - const servers = await composio.experimental.mcp.getServer(
708 - userId,
709 - mcpConfig.id
710 - );
711 -
712 - // Use servers with your AI framework
672 + const mcpConfig = await composio.mcp.create('server-name', {
673 + toolkits: serverConfigs,
674 + manuallyManageConnections: false,
675 + });
676 +
677 + const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
678 +
679 + // Use server instance with your MCP client
680 } catch (error) {
681 if (error instanceof ValidationError) {
682 console.error('Configuration error:', error.message);
@@ -727,83 +694,188 @@ Clean up MCP clients when done:
694 // For generic MCP clients
695 await mcpClient.close();
696
730 -// For Mastra clients
731 -await mcpClient.disconnect();
697 +// For Vercel AI MCP clients
698 +await mcpClient.close();
699 +```
700 +
701 +### 6. Server Instance Management
702 +
703 +Generate server instances per user to maintain proper isolation:
704 +
705 +```typescript
706 +// Good - separate instances for different users
707 +const userAInstance = await composio.mcp.generate('userA', mcpConfig.id);
708 +const userBInstance = await composio.mcp.generate('userB', mcpConfig.id);
709 +
710 +// Each user gets their own isolated MCP server URL
711 +console.log('User A MCP URL:', userAInstance.url);
712 +console.log('User B MCP URL:', userBInstance.url);
713 +```
714 +
715 +### 7. Pagination for Large Lists
716 +
717 +Use pagination when listing many MCP configurations:
718 +
719 +```typescript
720 +// Good - paginate through results
721 +let currentPage = 1;
722 +let hasMore = true;
723 +
724 +while (hasMore) {
725 + const result = await composio.mcp.list({
726 + page: currentPage,
727 + limit: 20
728 + });
729 +
730 + // Process result.items
731 + console.log(`Page ${currentPage}: ${result.items.length} items`);
732 +
733 + hasMore = currentPage < result.totalPages;
734 + currentPage++;
735 +}
736 ```
737
734 -## Migration from Standard MCP
738 +## Migration from Deprecated MCP API
739
736 -If you're using the standard MCP API, here's how to migrate:
740 +If you're using the deprecated MCP API, here's how to migrate:
741
738 -### Before (Standard MCP)
742 +### Before (Deprecated MCP API)
743
744 ```typescript
745 const composio = new Composio({
746 apiKey: process.env.COMPOSIO_API_KEY,
743 - provider: new AnthropicProvider()
747 + provider: new AnthropicProvider(),
748 });
749
746 -const server = await composio.mcp.create(
747 - "server-name",
750 +const server = await composio.deprecated.mcp.create(
751 + 'server-name',
752 [
753 {
750 - toolkit: "gmail",
751 - authConfigId: "ac_config",
752 - allowedTools: ["GMAIL_FETCH_EMAILS"]
753 - }
754 + authConfigId: 'ac_config',
755 + allowedTools: ['GMAIL_FETCH_EMAILS'],
756 + },
757 ],
758 { isChatAuth: true }
759 );
760
761 const urls = await server.getServer({
759 - userId: "user123"
762 + userId: 'user123',
763 });
764 ```
765
763 -### After (Experimental MCP)
766 +### After (Current MCP API)
767
768 ```typescript
769 const composio = new Composio({
770 apiKey: process.env.COMPOSIO_API_KEY,
768 - provider: new AnthropicProvider(),
771 });
772
771 -const mcpConfig = await composio.experimental.mcpConfig.create(
772 - "server-name",
773 - [
774 - {
775 - authConfigId: "ac_config",
776 - allowedTools: ["GMAIL_FETCH_EMAILS"]
777 - }
778 - ],
779 - { isChatAuth: true }
780 -);
773 +const mcpConfig = await composio.mcp.create('server-name', {
774 + toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_config' }],
775 + allowedTools: ['GMAIL_FETCH_EMAILS'],
776 + manuallyManageConnections: true, // Equivalent to isChatAuth: true
777 +});
778
782 -const servers = await composio.experimental.mcp.getServer(
783 - "user123",
784 - mcpConfig.id
785 -);
779 +const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
780 ```
781
782 +### Key Differences
783 +
784 +1. **API Location**: Moved from `composio.deprecated.mcp` to `composio.mcp`
785 +2. **Configuration Structure**: Simplified toolkit configuration with flexible options
786 +3. **Response Format**: Returns `MCPServerInstance` instead of provider-specific formats
787 +4. **Method Names**: `generate()` instead of `getServer()`
788 +5. **Authentication**: `manuallyManageConnections` instead of `isChatAuth`
789 +
790 ## Troubleshooting
791
792 ### Common Issues
793
792 -1. **Provider mismatch**: Ensure your provider supports the experimental MCP features
793 -2. **Auth config not found**: Verify your auth configuration IDs are correct
794 -3. **Tool not available**: Check that tools are properly configured in your auth config
795 -4. **Connection timeout**: MCP clients need to remain active while tools are being used
794 +1. **Auth config not found**: Verify your auth configuration IDs are correct and exist
795 + ```typescript
796 + // Verify auth config exists
797 + try {
798 + const authConfig = await composio.authConfigs.get('ac_your_config_id');
799 + console.log('Auth config found:', authConfig.toolkit);
800 + } catch (error) {
801 + console.error('Auth config not found:', error.message);
802 + }
803 + ```
804 +
805 +2. **Tool not available**: Check that tools are properly configured in your toolkit
806 + ```typescript
807 + // List available tools for a toolkit
808 + const tools = await composio.tools.list({ toolkit: 'gmail' });
809 + console.log('Available Gmail tools:', tools.map(t => t.slug));
810 + ```
811 +
812 +3. **Connection timeout**: MCP clients need to remain active while tools are being used
813 + ```typescript
814 + // Set appropriate timeouts for long-running operations
815 + const transport = new SSEClientTransport(new URL(serverInstance.url), {
816 + timeout: 30000 // 30 seconds
817 + });
818 + ```
819 +
820 +4. **Server instance not found**: Ensure the MCP configuration ID is valid
821 + ```typescript
822 + // Verify configuration exists before generating instance
823 + try {
824 + const config = await composio.mcp.get(mcpConfigId);
825 + const instance = await composio.mcp.generate(userId, mcpConfigId);
826 + } catch (error) {
827 + console.error('Configuration not found:', error.message);
828 + }
829 + ```
830 +
831 +5. **Validation errors**: Check that your configuration parameters are correct
832 + ```typescript
833 + // Ensure toolkits array is properly formatted
834 + const mcpConfig = await composio.mcp.create('server-name', {
835 + toolkits: [
836 + { toolkit: 'gmail', authConfigId: 'ac_valid_id' }, // Valid format
837 + 'github', // Also valid for default auth
838 + ],
839 + allowedTools: ['GMAIL_FETCH_EMAILS'], // Must be valid tool slugs
840 + manuallyManageConnections: false, // Must be boolean
841 + });
842 + ```
843
844 ### Debug Mode
845
846 Enable debug logging to troubleshoot issues:
847
848 ```typescript
849 +// Set environment variable for debug logging
850 +process.env.COMPOSIO_LOG_LEVEL = 'debug';
851 +
852 const composio = new Composio({
853 apiKey: process.env.COMPOSIO_API_KEY,
804 - provider: new AnthropicProvider(),
805 - // Additional debug configuration if available
854 +});
855 +
856 +// Additional debugging
857 +console.log('Composio config:', {
858 + baseURL: composio.config?.baseURL,
859 + hasApiKey: !!composio.config?.apiKey,
860 });
861 ```
862
809 -The experimental MCP API provides a powerful and flexible way to integrate Composio's tools with modern AI frameworks. By leveraging provider-specific optimizations and simplified configuration management, you can build more robust and maintainable AI applications.
863 +### Getting Help
864 +
865 +If you encounter issues:
866 +
867 +1. Check the [Composio documentation](https://docs.composio.dev)
868 +2. Review your auth configurations and connected accounts
869 +3. Verify that your MCP client is compatible with the Server-Sent Events transport
870 +4. Ensure your API key has the necessary permissions
871 +
872 +## Conclusion
873 +
874 +The MCP API provides a powerful and flexible way to integrate Composio's tools with modern AI frameworks through the Model Control Protocol. Key benefits include:
875 +
876 +- **Comprehensive management**: Full CRUD operations for MCP server configurations
877 +- **User isolation**: Generate unique server instances for individual users
878 +- **Flexible authentication**: Choose between Composio-managed or manual account management
879 +- **Universal compatibility**: Works with any MCP-compatible client
880 +
881 +By following the patterns and best practices outlined in this documentation, you can build robust and maintainable AI applications that leverage the full power of Composio's tool ecosystem through standardized MCP interfaces.
ts/docs/api/mcp.md
+292 -308
@@ -1,429 +1,413 @@
1 +# MCP API
2
2 -# MCP (Model Control Protocol) API
3 -
4 -The `MCP` class provides methods to manage Model Control Protocol servers, enabling AI models to interact with external tools and services through a standardized protocol. MCP servers act as bridges between AI agents and various toolkits, providing secure and managed access to external capabilities.
3 +The MCP (Model Control Protocol) API provides advanced server management capabilities for creating, configuring, and managing MCP servers with enhanced features.
4
5 ## Overview
6
8 -MCP (Model Control Protocol) is a protocol for exposing tools and capabilities to AI models in a standardized way. With Composio's MCP integration, you can:
9 -
10 -- Create MCP servers that expose specific toolkits and tools
11 -- Manage authentication for MCP servers
12 -- Generate secure URLs for AI agents to connect to MCP servers
13 -- Support multiple AI frameworks through provider-specific transformations
14 -
15 -## Methods
7 +The MCP class offers comprehensive CRUD operations for MCP servers, including:
8
17 -### create(name, toolkitConfigs, authOptions?)
9 +- Creating custom MCP configurations with toolkit-specific settings
10 +- Listing and filtering servers with pagination
11 +- Retrieving detailed server information
12 +- Updating server configurations
13 +- Deleting servers
14 +- Managing server instances for users
15
19 -Creates a new MCP server with specified toolkit configurations.
16 +## Getting Started
17
18 ```typescript
22 -// Create an MCP server with Gmail toolkit
23 -const server = await composio.mcp.create(
24 - "my-gmail-server",
25 - [
26 - {
27 - toolkit: "gmail",
28 - authConfigId: "ac_sdhkjfhjksdk",
29 - allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
30 - }
31 - ],
32 - { isChatAuth: true }
33 -);
19 +import { Composio } from '@composio/core';
20
35 -// Create an MCP server with multiple toolkits
36 -const multiToolServer = await composio.mcp.create(
37 - "multi-tool-server",
38 - [
21 +const composio = new Composio();
22 +const userId = "xxx-oooo-xxx";
23 +
24 +// create an MCP Server Config
25 +const server = await composio.mcp.create('my-mcp-server', {
26 + toolkits: [
27 {
40 - toolkit: "github",
41 - authConfigId: "ac_github123",
42 - allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_REPO"]
28 + toolkit: 'slack',
29 + authConfigId: 'ac_12324343',
30 + allowedTools: ['SLACK_SEND_MESSAGE'],
31 },
44 - {
45 - toolkit: "slack",
46 - authConfigId: "ac_slack456",
47 - allowedTools: ["SLACK_SEND_MESSAGE"]
48 - }
49 - ]
50 -);
51 -
52 -// Use the convenience method to get server URLs
53 -const urls = await server.getServer({
54 - connectedAccountIds: { gmail: "connected_account_id" }
32 + ],
33 });
34 +
35 +// get an instance for a user
36 +const mcp = await server.generate(userId);
37 +
38 +// using the global api
39 +const mcp = await composio.mcp.generate(userId, server.id);
40 +
41 +/** mcp
42 + * {
43 + * ...
44 + * id: "serverid",
45 + * url: "mcp-server.com/mcp",
46 + * ...
47 + * }
48 + * /
49 +
50 +// use the mcp with your mcp-client
51 ```
52
58 -**Parameters:**
53 +## Methods
54
60 -- `name` (string): Unique name for the MCP server
61 -- `toolkitConfigs` (MCPToolkitConfig[]): Array of toolkit configurations
62 - - `toolkit`: The toolkit slug (e.g., "gmail", "github")
63 - - `authConfigId`: The auth configuration ID to use
64 - - `allowedTools`: Array of specific tool IDs to expose
65 -- `authOptions` (MCPAuthOptions): Optional authentication options
66 - - `isChatAuth`: Whether to use Composio-managed authentication
55 +### create(name, config)
56
68 -**Returns:** Promise<McpServerCreateResponse> - Created server details with convenience `getServer` method
57 +Creates a new MCP server configuration with specified toolkits and authentication settings.
58
70 -**Throws:** ValidationError if configurations are invalid or server creation fails
59 +**Parameters:**
60
72 -### getServer(id, params, authOptions?)
61 +- `name` (string): Unique name for the MCP configuration
62 +- `config` (MCPConfigCreationParams): Configuration object containing:
63 + - `toolkits` (Array): Array of toolkit configurations
64 + - `toolkit` (string, optional): Toolkit identifier (e.g., "github", "slack")
65 + - `authConfigId` (string, optional): Auth configuration ID
66 + - `allowedTools` (string[], optional): Specific tools to enable
67 + - `manuallyManageConnections` (boolean, optional): Whether to manually manage account connections (default: false)
68
74 -Retrieves server URLs for an existing MCP server. This method generates secure URLs that AI agents can use to connect to the MCP server.
69 +**Returns:** `Promise<MCPConfigCreateResponse>`
70
76 -```typescript
77 -// Get URLs for a server using connected account IDs
78 -const urls = await composio.mcp.getServer("server-uuid", {
79 - connectedAccountIds: {
80 - gmail: "connected_account_123",
81 - github: "connected_account_456"
82 - }
83 -});
71 +**Example:**
72
85 -// Get URLs for a server using user ID
86 -const userUrls = await composio.mcp.getServer("server-uuid", {
87 - userId: "user_123"
73 +```typescript
74 +const server = await composio.mcp.create('personal-mcp-server', {
75 + toolkits: [
76 + {
77 + toolkit: 'github',
78 + authConfigId: 'ac_xyz',
79 + allowedTools: ['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS'],
80 + },
81 + {
82 + toolkit: 'slack',
83 + authConfigId: 'ac_abc',
84 + allowedTools: ['SLACK_SEND_MESSAGE'],
85 + },
86 + ],
87 + manuallyManageConnections: false,
88 });
89
90 -// Override authentication options
91 -const customAuthUrls = await composio.mcp.getServer(
92 - "server-uuid",
93 - { userId: "user_123" },
94 - { isChatAuth: false }
95 -);
90 +// Get server instance for a user
91 +const mcp = await server.generate('user_12345');
92 ```
93
98 -**Parameters:**
94 +### list(options)
95
100 -- `id` (string): Server UUID
101 -- `params` (MCPGetServerParams): Parameters for getting server URLs
102 - - Either `connectedAccountIds` (object mapping toolkit names to account IDs) OR `userId` (string)
103 -- `authOptions` (MCPAuthOptions): Optional authentication options to override server defaults
96 +Lists MCP servers with optional filtering and pagination.
97
105 -**Returns:** Promise<T> - Transformed server URLs in provider-specific format
98 +**Parameters:**
99
107 -**Throws:** ValidationError if parameters are invalid or URL generation fails
100 +- `options` (MCPListParams): Filtering and pagination options
101 + - `page` (number, optional): Page number for pagination (default: 1)
102 + - `limit` (number, optional): Maximum items per page (default: 10)
103 + - `toolkits` (string[], optional): Filter by toolkit names
104 + - `authConfigs` (string[], optional): Filter by auth configuration IDs
105 + - `name` (string, optional): Filter by server name (partial match)
106
109 -### list(options)
107 +**Returns:** `Promise<MCPListResponse>`
108
111 -Lists MCP server configurations with filtering options.
109 +**Example:**
110
111 ```typescript
114 -// List all servers with pagination
115 -const servers = await composio.mcp.list({
116 - page: 1,
117 - limit: 10
112 +// List all servers
113 +const allServers = await composio.mcp.list({});
114 +
115 +// Paginated listing
116 +const pagedServers = await composio.mcp.list({
117 + page: 2,
118 + limit: 5,
119 });
120
120 -// List servers for specific toolkits
121 -const gmailServers = await composio.mcp.list({
122 - toolkits: ['gmail', 'google-calendar'],
123 - limit: 20
121 +// Filter by toolkit
122 +const githubServers = await composio.mcp.list({
123 + toolkits: ['github', 'slack'],
124 });
125
126 -// List servers by auth config
127 -const authFilteredServers = await composio.mcp.list({
128 - authConfigs: ['auth_123', 'auth_456'],
129 - name: 'production'
126 +// Filter by name
127 +const personalServers = await composio.mcp.list({
128 + name: 'personal',
129 });
130 ```
131
133 -**Parameters:**
132 +### get(serverId)
133
135 -- `options` (object): Filtering and pagination options
136 - - `page`: Page number for pagination (default: 1)
137 - - `limit`: Number of items per page (default: 10)
138 - - `toolkits`: Filter by toolkit names
139 - - `authConfigs`: Filter by auth config IDs
140 - - `name`: Filter by server name
134 +Retrieves detailed information about a specific MCP server/config.
135
142 -**Returns:** Promise<McpListResponse> - List of MCP servers
136 +**Parameters:**
137 +
138 +- `serverId` (string): The unique identifier of the MCP server/config
139
144 -### get(id)
140 +**Returns:** `Promise<MCPItem>`
141
146 -Retrieves details of a specific MCP server.
142 +**Example:**
143
144 ```typescript
149 -const serverDetails = await composio.mcp.get('server-uuid');
150 -console.log(serverDetails.name);
151 -console.log(serverDetails.toolkits);
152 -console.log(serverDetails.status);
145 +const server = await composio.mcp.get('mcp_12345');
146 +
147 +console.log(server.name); // "My Personal MCP Server"
148 +console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
149 +console.log(server.toolkits); // ["github", "slack"]
150 +console.log(server.serverInstanceCount); // 3
151 +
152 +// Access setup commands for different clients
153 +console.log(server.commands.claude); // Claude setup command
154 +console.log(server.commands.cursor); // Cursor setup command
155 +console.log(server.commands.windsurf); // Windsurf setup command
156 ```
157
155 -**Parameters:**
158 +### update(serverId, config)
159
157 -- `id` (string): Server UUID
160 +Updates an existing MCP server configuration.
161 +
162 +**Parameters:**
163
159 -**Returns:** Promise<McpRetrieveResponse> - Server details including configuration and metadata
164 +- `serverId` (string): The unique identifier of the MCP server to update
165 +- `config` (MCPUpdateParams): Update configuration parameters
166 + - `name` (string, optional): New server name
167 + - `toolkits` (Array, optional): Updated toolkit configurations
168 + - `manuallyManageConnections` (boolean, optional): Connection management setting
169
161 -### update(id, name, toolkitConfigs, authOptions?)
170 +**Returns:** `Promise<MCPItem>`
171
163 -Updates an MCP server configuration.
172 +**Example:**
173
174 ```typescript
166 -const updatedServer = await composio.mcp.update(
167 - "server-uuid",
168 - "updated-server-name",
169 - [
175 +// Update server name only
176 +const updatedServer = await composio.mcp.update('mcp_12345', {
177 + name: 'My Updated MCP Server',
178 +});
179 +
180 +// Update toolkits and tools
181 +const serverWithNewTools = await composio.mcp.update('mcp_12345', {
182 + toolkits: [
183 + {
184 + toolkit: 'github',
185 + authConfigId: 'auth_abc123',
186 + allowedTools: ['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS'],
187 + },
188 {
171 - toolkit: "gmail",
172 - authConfigId: "ac_new_auth_config",
173 - allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL", "GMAIL_CREATE_DRAFT"]
174 - }
189 + toolkit: 'slack',
190 + authConfigId: 'auth_xyz789',
191 + allowedTools: ['SLACK_SEND_MESSAGE', 'SLACK_LIST_CHANNELS'],
192 + },
193 + ],
194 +});
195 +
196 +// Complete update
197 +const fullyUpdatedServer = await composio.mcp.update('mcp_12345', {
198 + name: 'Production MCP Server',
199 + toolkits: [
200 + {
201 + toolkit: 'gmail',
202 + authConfigId: 'auth_gmail_prod',
203 + allowedTools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],
204 + },
205 ],
176 - { isChatAtuh: true }
177 -);
206 + manuallyManageConnections: false,
207 +});
208 ```
209
180 -**Parameters:**
210 +### delete(serverId)
211
182 -- `id` (string): Server UUID
183 -- `name` (string): New name for the server
184 -- `toolkitConfigs` (MCPToolkitConfig[]): Updated toolkit configurations
185 -- `authOptions` (MCPAuthOptions): Updated authentication options
212 +Permanently deletes an MCP server configuration.
213 +
214 +**Parameters:**
215
187 -**Returns:** Promise<McpUpdateResponse> - Updated server details
216 +- `serverId` (string): The unique identifier of the MCP server to delete
217
189 -### delete(id)
218 +**Returns:** `Promise<{id: string; deleted: boolean}>`
219
191 -Deletes an MCP server.
220 +**Example:**
221
222 ```typescript
194 -const result = await composio.mcp.delete('server-uuid');
195 -console.log(result.deleted); // true
223 +// Delete a server
224 +const result = await composio.mcp.delete('mcp_12345');
225 +
226 +if (result.deleted) {
227 + console.log(`Server ${result.id} has been successfully deleted`);
228 +} else {
229 + console.log(`Failed to delete server ${result.id}`);
230 +}
231 +
232 +// With error handling
233 +try {
234 + const result = await composio.mcp.delete('mcp_12345');
235 + console.log('Deletion successful:', result);
236 +} catch (error) {
237 + console.error('Failed to delete MCP server:', error.message);
238 +}
239 +
240 +// Verify deletion
241 +await composio.mcp.delete('mcp_12345');
242 +const servers = await composio.mcp.list({});
243 +const serverExists = servers.items.some(server => server.id === 'mcp_12345');
244 +console.log('Server still exists:', serverExists); // Should be false
245 ```
246
198 -**Parameters:**
247 +### generate(userId, mcpConfigId, options?)
248 +
249 +Creates a server instance for a specific user.
250
200 -- `id` (string): Server UUID
251 +**Parameters:**
252
202 -**Returns:** Promise<McpDeleteResponse> - Deletion confirmation
253 +- `userId` (string): External user ID from your database
254 +- `mcpConfigId` (string): MCP configuration ID
255 +- `options` (MCPGetInstanceParams, optional): Additional options
256 + - `manuallyManageConnections` (boolean, optional): Whether to manually manage connections
257
204 -### generateUrl(params)
258 +**Returns:** `Promise<MCPServerInstance>`
259
206 -Generates URLs for MCP server access. This is a lower-level method primarily used internally.
260 +**Example:**
261
262 ```typescript
209 -const urlResponse = await composio.mcp.generateUrl({
210 - userIds: ['user123'],
211 - connectedAccountIds: ['account456'],
212 - mcpServerId: 'server-uuid',
213 - managedAuthByComposio: true
263 +const mcp = await composio.mcp.generate('user_12345', 'mcp_67890', {
264 + manuallyManageConnections: false,
265 });
266 +
267 +console.log(mcp.url); // Server URL for the user
268 +console.log(mcp.allowedTools); // Available tools
269 ```
270
217 -**Parameters:**
271 +## Data Types
272
219 -- `params` (GenerateURLParams): URL generation parameters
220 - - `userIds`: Array of user IDs
221 - - `connectedAccountIds`: Array of connected account IDs
222 - - `mcpServerId`: MCP server ID
223 - - `managedAuthByComposio`: Whether to use Composio-managed auth
273 +### MCPItem
274
225 -**Returns:** Promise<GenerateURLResponse> - Generated URLs
275 +Complete MCP server information including:
276
227 -## Provider Integration
277 +- `id`: Unique server identifier
278 +- `name`: Human-readable server name
279 +- `allowedTools`: Array of enabled tool identifiers
280 +- `authConfigIds`: Array of auth configuration IDs
281 +- `toolkits`: Array of toolkit names
282 +- `commands`: Setup commands for different clients (Claude, Cursor, Windsurf)
283 +- `MCPUrl`: Server connection URL
284 +- `toolkitIcons`: Map of toolkit icons
285 +- `serverInstanceCount`: Number of active instances
286
229 -Different AI frameworks expect MCP server URLs in different formats. Composio automatically handles these transformations through provider-specific implementations.
287 +### MCPListResponse
288
231 -### Using with Providers
289 +Paginated list response containing:
290
233 -```typescript
234 -import { Composio } from '@composio/core';
235 -import { MastraProvider } from '@composio/mastra';
236 -import { AnthropicProvider } from '@composio/anthropic';
291 +- `items`: Array of MCPItem objects
292 +- `currentPage`: Current page number
293 +- `totalPages`: Total number of pages
294
238 -// With Mastra provider - returns key-value URL mapping
239 -const composioMastra = new Composio({
240 - apiKey: process.env.COMPOSIO_API_KEY,
241 - provider: new MastraProvider()
242 -});
243 -
244 -const mastraServer = await composioMastra.mcp.create(...);
245 -const mastraUrls = await mastraServer.getServer({
246 - connectedAccountIds: { gmail: "account_id" }
247 -});
248 -// Returns: { "server-0": { url: "..." } }
295 +### MCPServerInstance
296
250 -// With Anthropic provider - returns array of server info
251 -const composioAnthropic = new Composio({
252 - apiKey: process.env.COMPOSIO_API_KEY,
253 - provider: new AnthropicProvider()
254 -});
297 +User-specific server instance containing:
298
256 -const anthropicServer = await composioAnthropic.mcp.create(...);
257 -const anthropicUrls = await anthropicServer.getServer({
258 - connectedAccountIds: { gmail: "account_id" }
259 -});
260 -// Returns: [{ url: URL, name: "...", toolkit: "gmail" }]
261 -```
299 +- `id`: Server identifier
300 +- `name`: Server name
301 +- `type`: Connection type (always 'streamable_http')
302 +- `url`: User-specific connection URL
303 +- `userId`: Associated user ID
304 +- `allowedTools`: Available tools for the user
305 +- `authConfigs`: Associated auth configurations
306
263 -### Supported Providers
307 +## Error Handling
308
265 -- **Anthropic** - Returns McpServerUrlInfo[]
266 -- **OpenAI** - Returns McpServerUrlInfo[]
267 -- **LangChain** - Returns McpServerUrlInfo[]
268 -- **Vercel** - Returns McpServerUrlInfo[]
269 -- **Google** - Returns McpServerUrlInfo[]
270 -- **CloudFlare** - Returns McpServerUrlInfo[]
271 -- **Mastra** - Returns custom key-value URL mapping
309 +All methods can throw the following exceptions:
310
273 -## Types
311 +- **ValidationError**: When input parameters are invalid or malformed
312 +- **Error**: When API operations fail (server not found, network issues, etc.)
313
275 -### MCPToolkitConfig
314 +### Example Error Handling
315
316 ```typescript
278 -interface MCPToolkitConfig {
279 - toolkit: string; // Toolkit slug (e.g., "gmail", "github")
280 - authConfigId: string; // Auth configuration ID
281 - allowedTools: string[]; // Array of allowed tool IDs
317 +try {
318 + const server = await composio.mcp.create('test-server', config);
319 +} catch (error) {
320 + if (error instanceof ValidationError) {
321 + console.error('Invalid configuration:', error.message);
322 + } else {
323 + console.error('API error:', error.message);
324 + }
325 }
326 ```
327
285 -### MCPAuthOptions
328 +## Best Practices
329
287 -```typescript
288 -interface MCPAuthOptions {
289 - isChatAuth?: boolean; // Use Composio-managed authentication
290 -}
291 -```
330 +### 1. Server Naming
331
293 -### MCPGetServerParams
332 +Use descriptive, unique names for your MCP servers:
333
334 ```typescript
296 -interface MCPGetServerParams {
297 - userId?: string; // User ID (XOR with connectedAccountIds)
298 - connectedAccountIds?: Record<string, string>; // Toolkit to account ID mapping
299 -}
335 +// Good
336 +'production-github-slack-server';
337 +'dev-testing-environment';
338 +'user-personal-tools';
339 +
340 +// Avoid
341 +'server1';
342 +'test';
343 +'mcp';
344 ```
345
302 -### McpServerCreateResponse
346 +### 2. Toolkit Configuration
347 +
348 +Be specific about allowed tools to maintain security:
349
350 ```typescript
305 -interface McpServerCreateResponse<T> {
306 - id: string; // Server UUID
307 - name: string; // Server name
308 - createdAt?: string; // Creation timestamp
309 - updatedAt?: string; // Last update timestamp
310 - status?: string; // Server status
311 - toolkits: string[]; // List of enabled toolkits
312 - getServer: (params: MCPGetServerParams) => Promise<T>; // Convenience method
351 +// Specific tools (recommended)
352 +{
353 + toolkit: "github",
354 + allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
355 }
314 -```
315 -
316 -### McpListResponse
356
318 -```typescript
319 -interface McpListResponse {
320 - items?: Array<{
321 - id: string;
322 - name: string;
323 - createdAt?: string;
324 - updatedAt?: string;
325 - status?: string;
326 - }>;
357 +// Avoid allowing all tools unless necessary
358 +{
359 + toolkit: "github"
360 + // No allowedTools = all tools enabled
361 }
362 ```
363
330 -### McpServerUrlInfo
364 +### 3. Connection Management
365 +
366 +Choose the appropriate connection management strategy:
367
368 ```typescript
333 -interface McpServerUrlInfo {
334 - url: URL; // MCP server URL
335 - name: string; // Server instance name
336 - toolkit?: string; // Associated toolkit
369 +// For chat based agents
370 +{
371 + manuallyManageConnections: false;
372 +}
373 +
374 +// For background agents, where you have to pre connect all the accounts
375 +{
376 + manuallyManageConnections: true;
377 }
378 ```
379
340 -## Complete Example
380 +### 4. Pagination
381
342 -Here's a complete example of using MCP with an AI agent:
382 +Use pagination for large server lists:
383
384 ```typescript
345 -import { Composio } from '@composio/core';
346 -import { MastraProvider } from '@composio/mastra';
347 -import { MCPClient } from '@mastra/mcp';
348 -import { Agent } from '@mastra/core/agent';
349 -import { openai } from '@ai-sdk/openai';
350 -
351 -// Initialize Composio with Mastra provider
352 -const composio = new Composio({
353 - apiKey: process.env.COMPOSIO_API_KEY,
354 - provider: new MastraProvider(),
355 -});
385 +let page = 1;
386 +let allServers = [];
387
357 -// Create an MCP server with Gmail toolkit
358 -const mcpServer = await composio.mcp.create(
359 - "gmail-assistant",
360 - [
361 - {
362 - toolkit: "gmail",
363 - authConfigId: "ac_your_auth_config",
364 - allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
365 - }
366 - ],
367 - { isChatAuth: true }
368 -);
388 +while (true) {
389 + const response = await composio.mcp.list({
390 + page,
391 + limit: 50,
392 + });
393
370 -// Get server URLs for connected accounts
371 -const serverUrls = await mcpServer.getServer({
372 - connectedAccountIds: {
373 - "gmail": "your_connected_account_id"
374 - }
375 -});
376 -
377 -// Initialize MCP client with the server URLs
378 -const mcpClient = new MCPClient({
379 - servers: Object.fromEntries(
380 - Object.entries(serverUrls).map(([key, value]) => [
381 - key,
382 - { url: new URL(value.url) }
383 - ])
384 - )
385 -});
394 + allServers.push(...response.items);
395
387 -// Get available tools from MCP
388 -const tools = await mcpClient.getTools();
389 -
390 -// Create an AI agent with MCP tools
391 -const gmailAgent = new Agent({
392 - name: 'Gmail Assistant',
393 - instructions: 'You are a helpful Gmail assistant.',
394 - model: openai('gpt-4'),
395 - tools,
396 -});
397 -
398 -// Use the agent
399 -const response = await gmailAgent.generate('Fetch my latest emails');
400 -console.log(response.text);
396 + if (page >= response.totalPages) break;
397 + page++;
398 +}
399 ```
400
403 -## Best Practices
404 -
405 -1. **Toolkit Selection**: Only expose the tools that your AI agent needs to minimize the attack surface
406 -2. **Authentication**: Use Composio-managed authentication when possible for better security
407 -3. **Error Handling**: Always handle validation errors when creating or updating servers
408 -4. **Provider Choice**: Choose the appropriate provider based on your AI framework
409 -5. **Server Naming**: Use descriptive names that indicate the server's purpose
410 -6. **Tool Allowlisting**: Be specific about which tools to expose rather than exposing entire toolkits
401 +## Limitations
402 +- Toolkit updates replace the entire configuration (no merging)
403 +- Deleted servers cannot be recovered
404 +- Server instances are tied to specific user IDs
405
412 -## Error Handling
406 +## Support
407
414 -All MCP methods throw `ValidationError` when:
415 -- Input parameters fail Zod schema validation
416 -- API responses don't match expected schemas
417 -- Server operations fail (create, update, delete)
418 -- URL generation fails
408 +For issues with the MCP API:
409
420 -```typescript
421 -try {
422 - const server = await composio.mcp.create("my-server", toolkitConfigs);
423 -} catch (error) {
424 - if (error instanceof ValidationError) {
425 - console.error('Validation failed:', error.message);
426 - console.error('Cause:', error.cause);
427 - }
428 -}
429 -```
\ No newline at end of file
410 +1. Check the error message for validation issues
411 +2. Verify your server configurations are valid
412 +3. Ensure you have proper permissions for the requested operations
413 +4. Contact support with specific error details and reproduction steps
ts/docs/api/mcp.old.md new
+429
@@ -0,0 +1,429 @@
1 +
2 +# MCP (Model Control Protocol) API
3 +
4 +The `MCP` class provides methods to manage Model Control Protocol servers, enabling AI models to interact with external tools and services through a standardized protocol. MCP servers act as bridges between AI agents and various toolkits, providing secure and managed access to external capabilities.
5 +
6 +## Overview
7 +
8 +MCP (Model Control Protocol) is a protocol for exposing tools and capabilities to AI models in a standardized way. With Composio's MCP integration, you can:
9 +
10 +- Create MCP servers that expose specific toolkits and tools
11 +- Manage authentication for MCP servers
12 +- Generate secure URLs for AI agents to connect to MCP servers
13 +- Support multiple AI frameworks through provider-specific transformations
14 +
15 +## Methods
16 +
17 +### create(name, toolkitConfigs, authOptions?)
18 +
19 +Creates a new MCP server with specified toolkit configurations.
20 +
21 +```typescript
22 +// Create an MCP server with Gmail toolkit
23 +const server = await composio.mcp.create(
24 + "my-gmail-server",
25 + [
26 + {
27 + toolkit: "gmail",
28 + authConfigId: "ac_sdhkjfhjksdk",
29 + allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
30 + }
31 + ],
32 + { isChatAuth: true }
33 +);
34 +
35 +// Create an MCP server with multiple toolkits
36 +const multiToolServer = await composio.mcp.create(
37 + "multi-tool-server",
38 + [
39 + {
40 + toolkit: "github",
41 + authConfigId: "ac_github123",
42 + allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_REPO"]
43 + },
44 + {
45 + toolkit: "slack",
46 + authConfigId: "ac_slack456",
47 + allowedTools: ["SLACK_SEND_MESSAGE"]
48 + }
49 + ]
50 +);
51 +
52 +// Use the convenience method to get server URLs
53 +const urls = await server.getServer({
54 + connectedAccountIds: { gmail: "connected_account_id" }
55 +});
56 +```
57 +
58 +**Parameters:**
59 +
60 +- `name` (string): Unique name for the MCP server
61 +- `toolkitConfigs` (MCPToolkitConfig[]): Array of toolkit configurations
62 + - `toolkit`: The toolkit slug (e.g., "gmail", "github")
63 + - `authConfigId`: The auth configuration ID to use
64 + - `allowedTools`: Array of specific tool IDs to expose
65 +- `authOptions` (MCPAuthOptions): Optional authentication options
66 + - `isChatAuth`: Whether to use Composio-managed authentication
67 +
68 +**Returns:** Promise<McpServerCreateResponse> - Created server details with convenience `getServer` method
69 +
70 +**Throws:** ValidationError if configurations are invalid or server creation fails
71 +
72 +### getServer(id, params, authOptions?)
73 +
74 +Retrieves server URLs for an existing MCP server. This method generates secure URLs that AI agents can use to connect to the MCP server.
75 +
76 +```typescript
77 +// Get URLs for a server using connected account IDs
78 +const urls = await composio.mcp.getServer("server-uuid", {
79 + connectedAccountIds: {
80 + gmail: "connected_account_123",
81 + github: "connected_account_456"
82 + }
83 +});
84 +
85 +// Get URLs for a server using user ID
86 +const userUrls = await composio.mcp.getServer("server-uuid", {
87 + userId: "user_123"
88 +});
89 +
90 +// Override authentication options
91 +const customAuthUrls = await composio.mcp.getServer(
92 + "server-uuid",
93 + { userId: "user_123" },
94 + { isChatAuth: false }
95 +);
96 +```
97 +
98 +**Parameters:**
99 +
100 +- `id` (string): Server UUID
101 +- `params` (MCPGetServerParams): Parameters for getting server URLs
102 + - Either `connectedAccountIds` (object mapping toolkit names to account IDs) OR `userId` (string)
103 +- `authOptions` (MCPAuthOptions): Optional authentication options to override server defaults
104 +
105 +**Returns:** Promise<T> - Transformed server URLs in provider-specific format
106 +
107 +**Throws:** ValidationError if parameters are invalid or URL generation fails
108 +
109 +### list(options)
110 +
111 +Lists MCP server configurations with filtering options.
112 +
113 +```typescript
114 +// List all servers with pagination
115 +const servers = await composio.mcp.list({
116 + page: 1,
117 + limit: 10
118 +});
119 +
120 +// List servers for specific toolkits
121 +const gmailServers = await composio.mcp.list({
122 + toolkits: ['gmail', 'google-calendar'],
123 + limit: 20
124 +});
125 +
126 +// List servers by auth config
127 +const authFilteredServers = await composio.mcp.list({
128 + authConfigs: ['auth_123', 'auth_456'],
129 + name: 'production'
130 +});
131 +```
132 +
133 +**Parameters:**
134 +
135 +- `options` (object): Filtering and pagination options
136 + - `page`: Page number for pagination (default: 1)
137 + - `limit`: Number of items per page (default: 10)
138 + - `toolkits`: Filter by toolkit names
139 + - `authConfigs`: Filter by auth config IDs
140 + - `name`: Filter by server name
141 +
142 +**Returns:** Promise<McpListResponse> - List of MCP servers
143 +
144 +### get(id)
145 +
146 +Retrieves details of a specific MCP server.
147 +
148 +```typescript
149 +const serverDetails = await composio.mcp.get('server-uuid');
150 +console.log(serverDetails.name);
151 +console.log(serverDetails.toolkits);
152 +console.log(serverDetails.status);
153 +```
154 +
155 +**Parameters:**
156 +
157 +- `id` (string): Server UUID
158 +
159 +**Returns:** Promise<McpRetrieveResponse> - Server details including configuration and metadata
160 +
161 +### update(id, name, toolkitConfigs, authOptions?)
162 +
163 +Updates an MCP server configuration.
164 +
165 +```typescript
166 +const updatedServer = await composio.mcp.update(
167 + "server-uuid",
168 + "updated-server-name",
169 + [
170 + {
171 + toolkit: "gmail",
172 + authConfigId: "ac_new_auth_config",
173 + allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL", "GMAIL_CREATE_DRAFT"]
174 + }
175 + ],
176 + { isChatAtuh: true }
177 +);
178 +```
179 +
180 +**Parameters:**
181 +
182 +- `id` (string): Server UUID
183 +- `name` (string): New name for the server
184 +- `toolkitConfigs` (MCPToolkitConfig[]): Updated toolkit configurations
185 +- `authOptions` (MCPAuthOptions): Updated authentication options
186 +
187 +**Returns:** Promise<McpUpdateResponse> - Updated server details
188 +
189 +### delete(id)
190 +
191 +Deletes an MCP server.
192 +
193 +```typescript
194 +const result = await composio.mcp.delete('server-uuid');
195 +console.log(result.deleted); // true
196 +```
197 +
198 +**Parameters:**
199 +
200 +- `id` (string): Server UUID
201 +
202 +**Returns:** Promise<McpDeleteResponse> - Deletion confirmation
203 +
204 +### generateUrl(params)
205 +
206 +Generates URLs for MCP server access. This is a lower-level method primarily used internally.
207 +
208 +```typescript
209 +const urlResponse = await composio.mcp.generateUrl({
210 + userIds: ['user123'],
211 + connectedAccountIds: ['account456'],
212 + mcpServerId: 'server-uuid',
213 + managedAuthByComposio: true
214 +});
215 +```
216 +
217 +**Parameters:**
218 +
219 +- `params` (GenerateURLParams): URL generation parameters
220 + - `userIds`: Array of user IDs
221 + - `connectedAccountIds`: Array of connected account IDs
222 + - `mcpServerId`: MCP server ID
223 + - `managedAuthByComposio`: Whether to use Composio-managed auth
224 +
225 +**Returns:** Promise<GenerateURLResponse> - Generated URLs
226 +
227 +## Provider Integration
228 +
229 +Different AI frameworks expect MCP server URLs in different formats. Composio automatically handles these transformations through provider-specific implementations.
230 +
231 +### Using with Providers
232 +
233 +```typescript
234 +import { Composio } from '@composio/core';
235 +import { MastraProvider } from '@composio/mastra';
236 +import { AnthropicProvider } from '@composio/anthropic';
237 +
238 +// With Mastra provider - returns key-value URL mapping
239 +const composioMastra = new Composio({
240 + apiKey: process.env.COMPOSIO_API_KEY,
241 + provider: new MastraProvider()
242 +});
243 +
244 +const mastraServer = await composioMastra.mcp.create(...);
245 +const mastraUrls = await mastraServer.getServer({
246 + connectedAccountIds: { gmail: "account_id" }
247 +});
248 +// Returns: { "server-0": { url: "..." } }
249 +
250 +// With Anthropic provider - returns array of server info
251 +const composioAnthropic = new Composio({
252 + apiKey: process.env.COMPOSIO_API_KEY,
253 + provider: new AnthropicProvider()
254 +});
255 +
256 +const anthropicServer = await composioAnthropic.mcp.create(...);
257 +const anthropicUrls = await anthropicServer.getServer({
258 + connectedAccountIds: { gmail: "account_id" }
259 +});
260 +// Returns: [{ url: URL, name: "...", toolkit: "gmail" }]
261 +```
262 +
263 +### Supported Providers
264 +
265 +- **Anthropic** - Returns McpServerUrlInfo[]
266 +- **OpenAI** - Returns McpServerUrlInfo[]
267 +- **LangChain** - Returns McpServerUrlInfo[]
268 +- **Vercel** - Returns McpServerUrlInfo[]
269 +- **Google** - Returns McpServerUrlInfo[]
270 +- **CloudFlare** - Returns McpServerUrlInfo[]
271 +- **Mastra** - Returns custom key-value URL mapping
272 +
273 +## Types
274 +
275 +### MCPToolkitConfig
276 +
277 +```typescript
278 +interface MCPToolkitConfig {
279 + toolkit: string; // Toolkit slug (e.g., "gmail", "github")
280 + authConfigId: string; // Auth configuration ID
281 + allowedTools: string[]; // Array of allowed tool IDs
282 +}
283 +```
284 +
285 +### MCPAuthOptions
286 +
287 +```typescript
288 +interface MCPAuthOptions {
289 + isChatAuth?: boolean; // Use Composio-managed authentication
290 +}
291 +```
292 +
293 +### MCPGetServerParams
294 +
295 +```typescript
296 +interface MCPGetServerParams {
297 + userId?: string; // User ID (XOR with connectedAccountIds)
298 + connectedAccountIds?: Record<string, string>; // Toolkit to account ID mapping
299 +}
300 +```
301 +
302 +### McpServerCreateResponse
303 +
304 +```typescript
305 +interface McpServerCreateResponse<T> {
306 + id: string; // Server UUID
307 + name: string; // Server name
308 + createdAt?: string; // Creation timestamp
309 + updatedAt?: string; // Last update timestamp
310 + status?: string; // Server status
311 + toolkits: string[]; // List of enabled toolkits
312 + getServer: (params: MCPGetServerParams) => Promise<T>; // Convenience method
313 +}
314 +```
315 +
316 +### McpListResponse
317 +
318 +```typescript
319 +interface McpListResponse {
320 + items?: Array<{
321 + id: string;
322 + name: string;
323 + createdAt?: string;
324 + updatedAt?: string;
325 + status?: string;
326 + }>;
327 +}
328 +```
329 +
330 +### McpServerUrlInfo
331 +
332 +```typescript
333 +interface McpServerUrlInfo {
334 + url: URL; // MCP server URL
335 + name: string; // Server instance name
336 + toolkit?: string; // Associated toolkit
337 +}
338 +```
339 +
340 +## Complete Example
341 +
342 +Here's a complete example of using MCP with an AI agent:
343 +
344 +```typescript
345 +import { Composio } from '@composio/core';
346 +import { MastraProvider } from '@composio/mastra';
347 +import { MCPClient } from '@mastra/mcp';
348 +import { Agent } from '@mastra/core/agent';
349 +import { openai } from '@ai-sdk/openai';
350 +
351 +// Initialize Composio with Mastra provider
352 +const composio = new Composio({
353 + apiKey: process.env.COMPOSIO_API_KEY,
354 + provider: new MastraProvider(),
355 +});
356 +
357 +// Create an MCP server with Gmail toolkit
358 +const mcpServer = await composio.mcp.create(
359 + "gmail-assistant",
360 + [
361 + {
362 + toolkit: "gmail",
363 + authConfigId: "ac_your_auth_config",
364 + allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
365 + }
366 + ],
367 + { isChatAuth: true }
368 +);
369 +
370 +// Get server URLs for connected accounts
371 +const serverUrls = await mcpServer.getServer({
372 + connectedAccountIds: {
373 + "gmail": "your_connected_account_id"
374 + }
375 +});
376 +
377 +// Initialize MCP client with the server URLs
378 +const mcpClient = new MCPClient({
379 + servers: Object.fromEntries(
380 + Object.entries(serverUrls).map(([key, value]) => [
381 + key,
382 + { url: new URL(value.url) }
383 + ])
384 + )
385 +});
386 +
387 +// Get available tools from MCP
388 +const tools = await mcpClient.getTools();
389 +
390 +// Create an AI agent with MCP tools
391 +const gmailAgent = new Agent({
392 + name: 'Gmail Assistant',
393 + instructions: 'You are a helpful Gmail assistant.',
394 + model: openai('gpt-4'),
395 + tools,
396 +});
397 +
398 +// Use the agent
399 +const response = await gmailAgent.generate('Fetch my latest emails');
400 +console.log(response.text);
401 +```
402 +
403 +## Best Practices
404 +
405 +1. **Toolkit Selection**: Only expose the tools that your AI agent needs to minimize the attack surface
406 +2. **Authentication**: Use Composio-managed authentication when possible for better security
407 +3. **Error Handling**: Always handle validation errors when creating or updating servers
408 +4. **Provider Choice**: Choose the appropriate provider based on your AI framework
409 +5. **Server Naming**: Use descriptive names that indicate the server's purpose
410 +6. **Tool Allowlisting**: Be specific about which tools to expose rather than exposing entire toolkits
411 +
412 +## Error Handling
413 +
414 +All MCP methods throw `ValidationError` when:
415 +- Input parameters fail Zod schema validation
416 +- API responses don't match expected schemas
417 +- Server operations fail (create, update, delete)
418 +- URL generation fails
419 +
420 +```typescript
421 +try {
422 + const server = await composio.mcp.create("my-server", toolkitConfigs);
423 +} catch (error) {
424 + if (error instanceof ValidationError) {
425 + console.error('Validation failed:', error.message);
426 + console.error('Cause:', error.cause);
427 + }
428 +}
429 +```
\ No newline at end of file
ts/docs/api/tool-router.experimental.md new
+508
@@ -0,0 +1,508 @@
1 +# ToolRouter Experimental API
2 +
3 +The ToolRouter Experimental API provides a powerful way to create isolated sessions for testing and managing tool routing logic with scoped access to multiple toolkits. This lab feature allows you to dynamically configure which tools are available within a session and manage their authentication configurations.
4 +
5 +## Overview
6 +
7 +The ToolRouter class enables you to:
8 +
9 +- Create isolated sessions with specific toolkit configurations
10 +- Manage authentication for multiple toolkits in a single session
11 +- Provide scoped MCP server access for testing and development
12 +- Route tool calls efficiently across different services
13 +
14 +## Getting Started
15 +
16 +```typescript
17 +import { Composio } from '@composio/core';
18 +
19 +const composio = new Composio();
20 +const userId = "xxx-ooo-xxx";
21 +
22 +// Access the experimental ToolRouter for specific toolkits
23 +const mcpSession = composio.experimental.toolRouter.createSession(userId, {
24 + toolkits: ["github"]
25 +});
26 +
27 +// Access the experimental ToolRouter for specific auth configs
28 +const mcpSession = composio.experimental.toolRouter.createSession(userId, {
29 + toolkits: [{
30 + toolkit: "github",
31 + authConfigId: "ac_xyz"
32 + }]
33 +});
34 +
35 +```
36 +
37 +## Methods
38 +
39 +### createSession(userId, routerConfig)
40 +
41 +Creates a new isolated session for the tool router with specified toolkits and authentication configurations. If no toolkits are provided, your router will have access to all the toolkits.
42 +
43 +**Parameters:**
44 +
45 +- `userId` (string): Unique user identifier for the session owner
46 +- `routerConfig` (ToolRouterConfig): Configuration object containing:
47 + - `toolkits` (Array): Array of toolkit configurations
48 + - `toolkit` (string): Toolkit identifier (e.g., "gmail", "slack", "github")
49 + - `authConfigId` (string, optional): Specific auth configuration ID for this toolkit
50 + - `manuallyManageConnections` (boolean, optional): Whether to disable Composio's automatic account management tools (default: false)
51 +
52 +**Returns:** `Promise<ToolRouterSession>`
53 +
54 +**Example:**
55 +
56 +```typescript
57 +// Basic session with multiple toolkits
58 +const session = await composio.experimental.toolRouter.createSession('user_123456789', {
59 + toolkits: ["gmail", "slack", "github", "hackernews"]
60 +});
61 +
62 +console.log('Session ID:', session.sessionId);
63 +console.log('MCP URL:', session.url);
64 +
65 +// Session with manual connection management and authConfigs
66 +const manualSession = await composio.experimental.toolRouter.createSession('user_789', {
67 + toolkits: [
68 + {
69 + toolkit: 'slack',
70 + authConfigId: 'ac_custom_slack',
71 + },
72 + ],
73 + manuallyManageConnections: true,
74 +});
75 +
76 +// Use the session URL with your MCP client
77 +const mcpClient = new MCPClient(session.url);
78 +```
79 +
80 +## Data Types
81 +
82 +### ToolRouterConfig
83 +
84 +Configuration object for creating a tool router session:
85 +
86 +```typescript
87 +interface ToolRouterConfig {
88 + toolkits?: string[] | ToolRouterToolkitConfig[];
89 + manuallyManageConnections?: boolean; // Disables automatic account management tools
90 +}
91 +```
92 +
93 +### ToolRouterToolkitConfig
94 +
95 +Individual toolkit configuration within a router config:
96 +
97 +```typescript
98 +interface ToolRouterToolkitConfig {
99 + toolkit: string; // Toolkit identifier
100 + authConfigId?: string; // Optional auth configuration ID
101 +}
102 +```
103 +
104 +### ToolRouterSession
105 +
106 +Response object containing session details:
107 +
108 +```typescript
109 +interface ToolRouterSession {
110 + sessionId: string; // Generated session identifier
111 + url: string; // MCP server endpoint URL for this session
112 +}
113 +```
114 +
115 +## Usage Patterns
116 +
117 +### 1. Multi-Service Integration
118 +
119 +Create sessions that span multiple services for complex workflows:
120 +
121 +```typescript
122 +const integrationSession = await composio.experimental.toolRouter.createSession('user_456', {
123 + toolkits: [
124 + { toolkit: 'gmail', authConfigId: 'ac_gmail_work' },
125 + { toolkit: 'slack', authConfigId: 'ac_slack_team' },
126 + { toolkit: 'github', authConfigId: 'ac_github_personal' },
127 + { toolkit: 'notion', authConfigId: 'ac_notion_workspace' },
128 + { toolkit: 'calendar', authConfigId: 'ac_gcal_primary' },
129 + ],
130 +});
131 +
132 +// This session can now handle tools from all configured services
133 +```
134 +
135 +### 2. Development and Testing
136 +
137 +Create isolated environments for testing different tool combinations:
138 +
139 +```typescript
140 +const testSession = await composio.experimental.toolRouter.createSession('test_user', {
141 + toolkits: ["hackernews", "weatherapi", "calculator"]
142 +});
143 +
144 +// Perfect for testing tool routing logic without auth complexity
145 +```
146 +
147 +### 3. User-Specific Sessions
148 +
149 +Create personalized sessions with user-specific auth configurations:
150 +
151 +```typescript
152 +async function createUserSession(userId: string, userPreferences: any) {
153 + const userToolkits = [];
154 +
155 + if (userPreferences.email) {
156 + userToolkits.push({
157 + toolkit: 'gmail',
158 + authConfigId: `gmail_${userId}`,
159 + });
160 + }
161 +
162 + if (userPreferences.messaging) {
163 + userToolkits.push({
164 + toolkit: 'slack',
165 + authConfigId: `slack_${userId}`,
166 + });
167 + }
168 +
169 + if (userPreferences.coding) {
170 + userToolkits.push({
171 + toolkit: 'github',
172 + authConfigId: `github_${userId}`,
173 + });
174 + }
175 +
176 + return await composio.experimental.toolRouter.createSession(userId, {
177 + toolkits: userToolkits,
178 + manuallyManageConnections: false,
179 + });
180 +}
181 +```
182 +
183 +## Connection Management
184 +
185 +The `manuallyManageConnections` flag controls whether Composio automatically injects account management tools into your session.
186 +
187 +### Automatic Account Management (Default)
188 +
189 +When `manuallyManageConnections` is `false` or omitted, Composio injects helpful account management tools:
190 +
191 +1. Connection status checking tools - agents can verify if accounts are connected
192 +2. Connection URL generation tools - agents can prompt users to connect accounts
193 +3. Account linking helpers - streamlined authentication flows
194 +
195 +```typescript
196 +const autoSession = await composio.experimental.toolRouter.createSession('user_123', {
197 + toolkits: [
198 + { toolkit: 'gmail', authConfigId: 'gmail_config' },
199 + { toolkit: 'slack', authConfigId: 'slack_config' },
200 + ],
201 + // manuallyManageConnections defaults to false
202 +});
203 +```
204 +
205 +### Manual Connection Management
206 +
207 +When `manuallyManageConnections` is `true`, Composio disables automatic account management tools:
208 +
209 +```typescript
210 +const manualSession = await composio.experimental.toolRouter.createSession('user_123', {
211 + toolkits: [
212 + { toolkit: 'gmail', authConfigId: 'gmail_config' },
213 + { toolkit: 'slack', authConfigId: 'slack_config' },
214 + ],
215 + manuallyManageConnections: true,
216 +});
217 +
218 +// No account management tools are injected
219 +// You must manually ensure all required connections exist beforehand
220 +// Use the Composio SDK to pre-connect accounts:
221 +
222 +// Before creating the session, link accounts manually:
223 +const connectionRequest = await composio.connectedAccounts.link({
224 + userId: 'user_123',
225 + authConfigId: 'gmail_config',
226 +});
227 +// redirect user to the url to authenticate
228 +console.log(connectionRequest.redirectUrl);
229 +
230 +// wait for users to connect their account
231 +const connectedAccount = await connectionRequest.waitForConnection();
232 +
233 +// Now the session can use these pre-connected accounts
234 +// But agents cannot dynamically check status or prompt for new connections
235 +```
236 +
237 +### When to Use Each Approach
238 +
239 +**Use Automatic Account Management (`manuallyManageConnections: false`) when:**
240 +
241 +- Building interactive AI agents that can communicate with users
242 +- Creating chat-based applications where users can be prompted to connect accounts
243 +- Developing applications where connection status might change during runtime
244 +- You want agents to handle authentication flows dynamically
245 +
246 +**Use Manual Connection Management (`manuallyManageConnections: true`) when:**
247 +
248 +- Building automated background processes or workflows
249 +- Creating production systems where all connections are pre-configured
250 +- You need predictable behavior without user interaction
251 +- Security requirements mandate pre-approved connections only
252 +- Building server-side applications without user interface
253 +
254 +```typescript
255 +// Interactive AI Assistant - use automatic management
256 +const assistantSession = await toolRouter.createSession('user_456', {
257 + toolkits: [
258 + { toolkit: 'gmail', authConfigId: 'user_gmail' },
259 + { toolkit: 'calendar', authConfigId: 'user_calendar' },
260 + ],
261 + manuallyManageConnections: false, // Agent can prompt for connections
262 +});
263 +
264 +// Background Automation - use manual management
265 +const automationSession = await toolRouter.createSession('automation_service', {
266 + toolkits: [
267 + { toolkit: 'gmail', authConfigId: 'service_gmail' },
268 + { toolkit: 'sheets', authConfigId: 'service_sheets' },
269 + ],
270 + manuallyManageConnections: true, // Pre-configured connections only
271 +});
272 +```
273 +
274 +## Integration with MCP Clients
275 +
276 +The ToolRouter sessions are designed to work seamlessly with MCP (Model Control Protocol) clients:
277 +
278 +```typescript
279 +// Create a session
280 +const session = await composio.experimental.toolRouter.createSession('user_456', {
281 + toolkits: [{ toolkit: 'gmail' }, { toolkit: 'slack' }, { toolkit: 'github' }],
282 +});
283 +
284 +// Use with Claude Desktop
285 +// Add to claude_desktop_config.json:
286 +/*
287 +{
288 + "mcpServers": {
289 + "composio-session": {
290 + "command": "npx",
291 + "args": ["@composio/core", "mcp"],
292 + "env": {
293 + "COMPOSIO_MCP_URL": session.url
294 + }
295 + }
296 + }
297 +}
298 +*/
299 +
300 +// Use with custom MCP client
301 +import { MCPClient } from 'your-mcp-client';
302 +
303 +const mcpClient = new MCPClient({
304 + serverUrl: session.url,
305 + sessionId: session.sessionId,
306 +});
307 +
308 +await mcpClient.connect();
309 +
310 +// Now you can use tools from all configured toolkits
311 +const emails = await mcpClient.callTool('gmail_fetch_emails', { limit: 10 });
312 +const channels = await mcpClient.callTool('slack_list_channels', {});
313 +const repos = await mcpClient.callTool('github_list_repos', { user: 'username' });
314 +```
315 +
316 +## Error Handling
317 +
318 +Handle common errors when creating sessions:
319 +
320 +```typescript
321 +try {
322 + const session = await composio.experimental.toolRouter.createSession(userId, config);
323 + console.log('Session created successfully:', session.sessionId);
324 +} catch (error) {
325 + if (error instanceof ValidationError) {
326 + console.error('Invalid configuration:', error.message);
327 + // Handle validation errors (malformed config, missing required fields)
328 + } else if (error.message.includes('auth_config')) {
329 + console.error('Authentication configuration error:', error.message);
330 + // Handle auth config issues (invalid IDs, permissions)
331 + } else if (error.message.includes('toolkit')) {
332 + console.error('Toolkit configuration error:', error.message);
333 + // Handle toolkit issues (unsupported toolkit, invalid name)
334 + } else {
335 + console.error('Unexpected error:', error.message);
336 + // Handle other API errors
337 + }
338 +}
339 +```
340 +
341 +## Best Practices
342 +
343 +### 1. Session Naming and Organization
344 +
345 +Use descriptive user IDs and maintain session records:
346 +
347 +```typescript
348 +// Good: Descriptive user identifiers
349 +const session = await toolRouter.createSession('user_john_doe_workspace_1', config);
350 +
351 +// Keep track of active sessions
352 +const activeSessions = new Map();
353 +activeSessions.set(userId, session);
354 +```
355 +
356 +### 2. Toolkit Selection
357 +
358 +Be intentional about which toolkits to include:
359 +
360 +```typescript
361 +// Good: Only include necessary toolkits
362 +const focusedSession = await toolRouter.createSession(userId, {
363 + toolkits: [
364 + { toolkit: 'gmail' }, // For email operations
365 + { toolkit: 'calendar' }, // For scheduling
366 + ],
367 +});
368 +
369 +// Avoid: Including unnecessary toolkits
370 +// This creates security risks and complexity
371 +```
372 +
373 +### 3. Auth Configuration Management
374 +
375 +Use specific auth configs for different contexts:
376 +
377 +```typescript
378 +// Production session
379 +const prodSession = await toolRouter.createSession(userId, {
380 + toolkits: [
381 + { toolkit: 'gmail', authConfigId: 'gmail_prod_config' },
382 + { toolkit: 'slack', authConfigId: 'slack_prod_workspace' },
383 + ],
384 +});
385 +
386 +// Development session
387 +const devSession = await toolRouter.createSession(userId, {
388 + toolkits: [
389 + { toolkit: 'gmail', authConfigId: 'gmail_dev_config' },
390 + { toolkit: 'slack', authConfigId: 'slack_dev_workspace' },
391 + ],
392 +});
393 +```
394 +
395 +### 4. Session Lifecycle Management
396 +
397 +Implement proper session cleanup:
398 +
399 +```typescript
400 +class SessionManager {
401 + private sessions = new Map<string, ToolRouterSession>();
402 +
403 + async createUserSession(userId: string, config: ToolRouterConfig) {
404 + // Clean up existing session if any
405 + if (this.sessions.has(userId)) {
406 + await this.cleanupSession(userId);
407 + }
408 +
409 + const session = await toolRouter.createSession(userId, config);
410 + this.sessions.set(userId, session);
411 +
412 + // Set cleanup timer (optional)
413 + setTimeout(() => this.cleanupSession(userId), 24 * 60 * 60 * 1000); // 24 hours
414 +
415 + return session;
416 + }
417 +
418 + async cleanupSession(userId: string) {
419 + // Implement session cleanup logic
420 + this.sessions.delete(userId);
421 + }
422 +}
423 +```
424 +
425 +## Use Cases
426 +
427 +### 1. AI Assistant Integration
428 +
429 +Create dynamic sessions for AI assistants that need access to multiple services:
430 +
431 +```typescript
432 +const assistantSession = await toolRouter.createSession('assistant_user_123', {
433 + toolkits: [
434 + { toolkit: 'gmail', authConfigId: 'user_email' },
435 + { toolkit: 'calendar', authConfigId: 'user_calendar' },
436 + { toolkit: 'slack', authConfigId: 'user_slack' },
437 + { toolkit: 'github', authConfigId: 'user_github' },
438 + ],
439 +});
440 +
441 +// AI can now help with email, scheduling, team communication, and code
442 +```
443 +
444 +### 2. Workflow Automation
445 +
446 +Set up sessions for automated workflows:
447 +
448 +```typescript
449 +const workflowSession = await toolRouter.createSession('workflow_engine', {
450 + toolkits: [
451 + { toolkit: 'gmail' },
452 + { toolkit: 'slack' },
453 + { toolkit: 'sheets' },
454 + { toolkit: 'notion' },
455 + ],
456 + manuallyManageConnections: true, // Pre-configured connections
457 +});
458 +
459 +// Automated workflow can process emails, update spreadsheets, notify teams
460 +```
461 +
462 +### 3. Customer Support Tools
463 +
464 +Create specialized sessions for support agents:
465 +
466 +```typescript
467 +const supportSession = await toolRouter.createSession(`support_agent_${agentId}`, {
468 + toolkits: [
469 + { toolkit: 'zendesk', authConfigId: 'support_zendesk' },
470 + { toolkit: 'slack', authConfigId: 'support_slack' },
471 + { toolkit: 'gmail', authConfigId: 'support_email' },
472 + { toolkit: 'sheets', authConfigId: 'support_tracking' },
473 + ],
474 +});
475 +
476 +// Support agents can access tickets, communicate with team, send emails, track metrics
477 +```
478 +
479 +## Limitations and Considerations
480 +
481 +- **Session Isolation**: Each session is isolated and cannot directly communicate with other sessions
482 +- **Resource Limits**: There may be limits on the number of concurrent sessions per user
483 +- **Auth Config Requirements**: Some toolkits require specific auth configurations to function properly
484 +- **Session Persistence**: Sessions may have time limits and need to be refreshed periodically
485 +- **Toolkit Compatibility**: Not all toolkit combinations may work optimally together
486 +
487 +## Migration and Compatibility
488 +
489 +The ToolRouter experimental API is designed to complement existing Composio features:
490 +
491 +```typescript
492 +// Can be used alongside regular MCP servers
493 +const regularMCP = await composio.mcp.create('regular-server', serverConfig, options);
494 +const routerSession = await composio.experimental.toolRouter.createSession(userId, routerConfig);
495 +
496 +// Both can coexist and serve different purposes
497 +```
498 +
499 +## Support and Troubleshooting
500 +
501 +For issues with the ToolRouter Experimental API:
502 +
503 +1. **Validation Errors**: Check that all required fields are provided and toolkit names are correct
504 +2. **Auth Configuration Issues**: Verify that auth config IDs exist and have proper permissions
505 +3. **Connection Problems**: Ensure network connectivity and proper MCP client configuration
506 +4. **Toolkit Compatibility**: Some toolkits may have specific requirements or limitations
507 +
508 +For additional support, consult the Composio documentation or contact support with session details and error messages.
ts/examples/anthropic/src/experimental.mcp.ts
+15 -11
@@ -5,7 +5,7 @@ import Anthropic from '@anthropic-ai/sdk';
5 // 1. Initialize Composio.
6 const composio = new Composio({
7 apiKey: process.env.COMPOSIO_API_KEY,
8 - provider: new AnthropicProvider({ cacheTools: true })
8 + provider: new AnthropicProvider({ cacheTools: true }),
9 });
10
11 const authConfigId = '<auth_config_id>'; // Use your auth config ID
@@ -13,21 +13,19 @@ const externalUserId = '<external_user_id>'; // Replace it with the your user id
13 const allowedTools = ['GMAIL_FETCH_EMAILS'];
14
15 // 2. Create an MCP config
16 -const mcpConfig = await composio.experimental.mcpConfig.create(
17 - `${Date.now()}`,
18 - [
16 +const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
17 + toolkits: [
18 {
19 + toolkit: 'gmail',
20 authConfigId,
21 - allowedTools,
21 },
22 ],
24 - { isChatAuth: true }
25 -);
23 + allowedTools,
24 + manuallyManageConnections: true,
25 +});
26
27 // 3. Retrieve the MCP server instance for the connected accounts
28 -const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
29 - limitTools: allowedTools,
30 -});
28 +const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
29
30 // 4. Initialize Anthropic client.
31 const anthropic = new Anthropic({
@@ -38,7 +36,13 @@ const anthropic = new Anthropic({
36 const stream = anthropic.beta.messages.stream({
37 model: 'claude-4-sonnet-20250514',
38 max_tokens: 64_000,
41 - mcp_servers: servers,
39 + mcp_servers: [
40 + {
41 + name: mcp.name,
42 + url: mcp.url,
43 + type: 'url',
44 + },
45 + ],
46 messages: [
47 {
48 role: 'user',
ts/examples/google/src/experimental.mcp.ts
+7 -10
@@ -19,27 +19,24 @@ const externalUserId = '<externalUserId>'; // Replace it with the user id from y
19 const allowedTools = ['GMAIL_FETCH_EMAILS'];
20
21 // 2. Create an MCP config
22 -const mcpConfig = await composio.experimental.mcpConfig.create(
23 - `${Date.now()}`,
24 - [
22 +const mcpConfig = await composio.experimental.mcp.create(`${Date.now()}`, {
23 + toolkits: [
24 {
26 - // https://platform.composio.dev/alberto_schiabel/2025-09-12/auth-configs/ac_ydsgH6ZRO1Xc
25 + toolkit: 'gmail',
26 authConfigId,
27 allowedTools,
28 },
29 ],
31 - { isChatAuth: true }
32 -);
30 + manuallyManageConnections: true,
31 +});
32
33 // 3. Retrieve the MCP server instance for the user
35 -const url = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
36 - limitTools: allowedTools,
37 -});
34 +const server = await composio.experimental.mcp.generate(externalUserId, mcpConfig.id);
35
36 // 4. Create a generic MCP client.
37 // This client needs to remain "alive" not be dropped by the GC until
38 // the tools are retrieved from it.
42 -const serverParams = new SSEClientTransport(url);
39 +const serverParams = new SSEClientTransport(new URL(server.url));
40 const mcpClient = new MCPClient({
41 name: 'composio-mcp-client',
42 version: '1.0.0',
ts/examples/mastra/src/experimental.mcp.ts
+14 -32
@@ -4,29 +4,10 @@ import { MastraProvider } from '@composio/mastra';
4 import { MCPClient as MastraMCPClient } from '@mastra/mcp';
5 import { Agent as MastraAgent } from '@mastra/core/agent';
6
7 -function wrapTools(servers: Record<string, any>, tools: Record<string, any>): Record<string, any> {
8 - const prefixes = Object.keys(servers);
9 -
10 - function removePrefix(str: string): string {
11 - for (const prefix of prefixes) {
12 - if (str.startsWith(prefix)) {
13 - return str.slice(prefix.length + 1);
14 - }
15 - }
16 - return str;
17 - }
18 -
19 - return Object.fromEntries(
20 - Object.entries(tools).map(([key, tool]) => {
21 - return [removePrefix(key), tool] as const;
22 - })
23 - );
24 -}
25 -
7 // 1. Initialize Composio.
8 const composio = new Composio({
9 apiKey: process.env.COMPOSIO_API_KEY,
29 - provider: new MastraProvider()
10 + provider: new MastraProvider(),
11 });
12
13 const authConfigId = '<auth_config_id>'; // Use your auth config ID
@@ -34,28 +15,29 @@ const externalUserId = '<external_user_id>'; // Replace it with the user id id
15 const allowedTools = ['GMAIL_FETCH_EMAILS'];
16
17 // 2. Create an MCP config
37 -const mcpConfig = await composio.experimental.mcpConfig.create(
38 - `${Date.now()}`,
39 - [
18 +const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
19 + toolkits: [
20 {
41 - // https://platform.composio.dev/alberto_schiabel/2025-09-12/auth-configs/ac_uINV_uCV87lm
21 + toolkit: 'gmail',
22 authConfigId,
43 - allowedTools,
23 },
24 ],
46 - { isChatAuth: true }
47 -);
25 + allowedTools,
26 + manuallyManageConnections: true,
27 +});
28
29 // 3. Retrieve the MCP server instance for the user
50 -const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
51 - limitTools: allowedTools,
52 -});
30 +const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
31
32 // 4. Create a Mastra-specific MCP client.
33 // This client needs to remain "alive" not be dropped by the GC until
34 // the tools are retrieved from it.
35 const mcpClient = new MastraMCPClient({
58 - servers,
36 + servers: {
37 + composio: {
38 + url: new URL(mcp.url),
39 + },
40 + },
41 });
42
43 // 5. Retrieve tools.
@@ -70,7 +52,7 @@ const agent = new MastraAgent({
52 Be concise and provide actionable information based on the email content.
53 `,
54 model: openai('gpt-4o-mini'),
73 - tools: wrapTools(servers, tools),
55 + tools,
56 });
57
58 // Fetch and summarize recent emails.
ts/examples/mastra/src/experimental.tool-router.ts new
+59
@@ -0,0 +1,59 @@
1 +import { openai } from '@ai-sdk/openai';
2 +import { Composio } from '@composio/core';
3 +import { MastraProvider } from '@composio/mastra';
4 +import { MCPClient as MastraMCPClient } from '@mastra/mcp';
5 +import { Agent as MastraAgent } from '@mastra/core/agent';
6 +
7 +// 1. Initialize Composio.
8 +const composio = new Composio({
9 + apiKey: process.env.COMPOSIO_API_KEY,
10 + provider: new MastraProvider(),
11 +});
12 +
13 +const externalUserId = '<external_user_id>'; // Replace it with the user id id
14 +
15 +// 2. Create an tool router session
16 +const mcpSession = await composio.experimental.toolRouter.createSession(externalUserId, {
17 + toolkits: ["gmail"],
18 + manuallyManageConnections: true,
19 +});
20 +
21 +
22 +// 3. Create a Mastra-specific MCP client.
23 +// This client needs to remain "alive" not be dropped by the GC until
24 +// the tools are retrieved from it.
25 +const mcpClient = new MastraMCPClient({
26 + servers: {
27 + composio: {
28 + url: new URL(mcpSession.url),
29 + },
30 + },
31 +});
32 +
33 +// 4. Retrieve tools.
34 +const tools = await mcpClient.getTools();
35 +
36 +// 5. Pass tools to Mastra-specific Agent.
37 +const agent = new MastraAgent({
38 + name: 'Gmail Assistant',
39 + instructions: `
40 + You are a helpful Gmail assistant that fetches and summarizes emails.
41 + When fetching emails, provide a clear summary of the results including sender, subject, and date.
42 + Be concise and provide actionable information based on the email content.
43 + `,
44 + model: openai('gpt-4o-mini'),
45 + tools,
46 +});
47 +
48 +// Fetch and summarize recent emails.
49 +console.log('\n=== Fetching and Summarizing Recent Emails ===');
50 +const emailResponse = await agent.generate(
51 + 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
52 +);
53 +console.log('\n📬 Email Summary:');
54 +console.log(emailResponse.text);
55 +
56 +console.log('\n✅ Gmail MCP Example completed successfully!');
57 +
58 +// 8. Close Mastra-specific MCP client.
59 +await mcpClient.disconnect();
ts/examples/mcp/.env.example new
+6
@@ -0,0 +1,6 @@
1 +# Composio API Key - Get it from https://app.composio.dev
2 +COMPOSIO_API_KEY=your_composio_api_key_here
3 +
4 +# Add other environment variables as needed for your example
5 +# OPENAI_API_KEY=your_openai_api_key_here
6 +# ANTHROPIC_API_KEY=your_anthropic_api_key_here
ts/examples/mcp/README.md new
+53
@@ -0,0 +1,53 @@
1 +# Mcp Example
2 +
3 +This example demonstrates how to use Composio SDK for mcp.
4 +
5 +## Setup
6 +
7 +1. **Install dependencies:**
8 + ```bash
9 + pnpm install
10 + ```
11 +
12 +2. **Configure environment:**
13 + ```bash
14 + cp .env.example .env
15 + ```
16 +
17 + Then edit `.env` and add your API keys:
18 + - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
19 +
20 +## Running the Example
21 +
22 +```bash
23 +# Run the example
24 +pnpm start
25 +
26 +# Run in development mode (with file watching)
27 +pnpm dev
28 +```
29 +
30 +## What This Example Does
31 +
32 +- Initializes Composio SDK
33 +- Fetches available tools
34 +- Demonstrates basic usage patterns
35 +
36 +## Customization
37 +
38 +Edit `src/index.ts` to:
39 +- Add specific apps you want to integrate with
40 +- Implement your business logic
41 +- Add error handling and logging
42 +
43 +## Related Examples
44 +
45 +- [OpenAI Example](../openai) - Shows integration with OpenAI
46 +- [LangChain Example](../langchain) - Shows integration with LangChain
47 +- [More Examples](../) - Browse all available examples
48 +
49 +## Support
50 +
51 +- [Documentation](https://docs.composio.dev)
52 +- [Discord Community](https://discord.gg/composio)
53 +- [GitHub Issues](https://github.com/composio/composio/issues)
ts/examples/mcp/package.json new
+32
@@ -0,0 +1,32 @@
1 +{
2 + "name": "mcp-example",
3 + "private": true,
4 + "version": "0.1.0",
5 + "description": "Example project for Mcp",
6 + "main": "src/index.ts",
7 + "scripts": {
8 + "start": "bun src/index.ts",
9 + "dev": "bun --watch src/index.ts",
10 + "test": "echo \"Error: no test specified\" && exit 1"
11 + },
12 + "keywords": [
13 + "composio",
14 + "example",
15 + "mcp"
16 + ],
17 + "author": "",
18 + "license": "ISC",
19 + "packageManager": "pnpm@10.17.0",
20 + "dependencies": {
21 + "@ai-sdk/openai": "^2.0.35",
22 + "@composio/core": "workspace:*",
23 + "@composio/vercel": "workspace:*",
24 + "@modelcontextprotocol/sdk": "^1.18.0",
25 + "ai": "catalog:",
26 + "dotenv": "^16.4.1"
27 + },
28 + "devDependencies": {
29 + "@types/bun": "^1.2.9",
30 + "typescript": "catalog:"
31 + }
32 +}
ts/examples/mcp/src/index.ts new
+62
@@ -0,0 +1,62 @@
1 +import { openai } from '@ai-sdk/openai';
2 +import { Composio } from '@composio/core';
3 +import { VercelProvider } from '@composio/vercel';
4 +import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
5 +import { experimental_createMCPClient as createMCPClient, stepCountIs, streamText } from 'ai';
6 +import 'dotenv/config';
7 +
8 +// 1. Initialize Composio.
9 +const composio = new Composio({
10 + apiKey: process.env.COMPOSIO_API_KEY,
11 + provider: new VercelProvider(),
12 +});
13 +
14 +const authConfigId = '<auth_config_id>'; // Use your auth config ID
15 +const externalUserId = '<extern_user_id>'; // Replace it with the user id
16 +const allowedTools = ['GMAIL_FETCH_EMAILS'];
17 +
18 +// 2. Create an MCP config
19 +const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
20 + toolkits: [
21 + {
22 + toolkit: 'gmail',
23 + authConfigId,
24 + },
25 + ],
26 + allowedTools,
27 + manuallyManageConnections: false,
28 +});
29 +
30 +// 3. Retrieve the MCP server instance for the user
31 +const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
32 +
33 +const serverParams = new SSEClientTransport(new URL(server.url));
34 +
35 +const mcpClient = await createMCPClient({
36 + name: 'composio-mcp-client',
37 + transport: serverParams,
38 +});
39 +
40 +// 5. Retrieve tools.
41 +const tools = await mcpClient.tools();
42 +
43 +// 6. Pass tools to Vercel-specific Agent.
44 +const stream = streamText({
45 + model: openai('gpt-4o-mini'),
46 + messages: [
47 + {
48 + role: 'user',
49 + content: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,
50 + },
51 + ],
52 + stopWhen: stepCountIs(5),
53 + tools,
54 +});
55 +
56 +// 7. Execute the Vercel AI-specific Agent.
57 +for await (const textPart of stream.textStream) {
58 + process.stdout.write(textPart);
59 +}
60 +
61 +// 8. Close Vercel AI's MCP client.
62 +await mcpClient.close();
ts/examples/mcp/tsconfig.json new
+16
@@ -0,0 +1,16 @@
1 +{
2 + "compilerOptions": {
3 + "target": "es2022",
4 + "module": "esnext",
5 + "declaration": true,
6 + "declarationDir": "./dist",
7 + "outDir": "./dist",
8 + "rootDir": "./src",
9 + "strict": true,
10 + "esModuleInterop": true,
11 + "moduleResolution": "bundler",
12 + "skipLibCheck": true,
13 + "resolveJsonModule": true
14 + },
15 + "include": ["src"]
16 +}
ts/examples/openai/package.json
+1 -1
@@ -23,7 +23,7 @@
23 "@composio/openai": "workspace:*",
24 "@composio/openai-agents": "workspace:*",
25 "@modelcontextprotocol/sdk": "^1.18.0",
26 - "@openai/agents": "^0.1.3",
26 + "@openai/agents": "^0.1.4",
27 "dotenv": "^16.4.1",
28 "openai": "^5.16.0",
29 "zod": "catalog:",
ts/examples/openai/src/agents-api/experiment.mcp.ts
+21 -35
@@ -1,55 +1,41 @@
1 import { Composio } from '@composio/core';
2 import { OpenAIAgentsProvider } from '@composio/openai-agents';
3 -import { Agent as OpenAIAgent, run } from '@openai/agents';
3 +import { hostedMcpTool, Agent as OpenAIAgent, run } from '@openai/agents';
4 import type { HostedMCPTool } from '@openai/agents';
5 import 'dotenv/config';
6
7 -function sanitizeString(input: string): string {
8 - return input.replace(/[^a-zA-Z0-9_-]+/g, '-');
9 -}
10 -
11 -function wrapTools<T>(servers: Array<HostedMCPTool<T>>): Array<HostedMCPTool<T>> {
12 - return servers.map(server => {
13 - const { server_label, ...rest } = server.providerData ?? {};
14 - return {
15 - ...server,
16 - providerData: {
17 - ...rest,
18 - /**
19 - * 'server_label' must start with a letter and consist of only letters, digits, '-' and '_'
20 - */
21 - server_label: sanitizeString(server_label),
22 - },
23 - };
24 - });
25 -}
26 -
7 // 1. Initialize Composio.
8 const composio = new Composio({
9 apiKey: process.env.COMPOSIO_API_KEY,
10 provider: new OpenAIAgentsProvider(),
11 + allowTracking: false,
12 });
13
14 const authConfigId = '<auth_config_id>'; // Use your auth config ID
15 +const toolkit = 'gmail'; // slug of the toolkit
16 const externalUserId = '<external_user_id>'; // Replace it with the userId from your database
17 const allowedTools = ['GMAIL_FETCH_EMAILS'];
18
19 // 2. Create an MCP config
38 -const mcpConfig = await composio.experimental.mcpConfig.create(
39 - `gmail-mcp-${Date.now()}`,
40 - [
41 - {
42 - authConfigId,
43 - allowedTools,
44 - },
45 - ],
46 - { isChatAuth: true }
47 -);
20 +const mcpConfig = await composio.mcp.create(externalUserId, {
21 + toolkits: [{ toolkit, authConfigId }],
22 + allowedTools,
23 +});
24
25 // 3. Retrieve the MCP server instance for the connected accounts
50 -const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
51 - limitTools: allowedTools,
52 -});
26 +const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
27 +
28 +const tools: HostedMCPTool[] = [
29 + hostedMcpTool({
30 + serverLabel: server.name,
31 + serverUrl: server.url,
32 + requireApproval: {
33 + never: {
34 + toolNames: ['GMAIL_FETCH_EMAILS'],
35 + },
36 + },
37 + }),
38 +];
39
40 // 4. Pass tools to OpenAI-specific Agent.
41 const agent = new OpenAIAgent({
@@ -60,7 +46,7 @@ const agent = new OpenAIAgent({
46 Be concise and provide actionable information based on the email content.
47 `,
48 model: 'gpt-4o-mini',
63 - tools: wrapTools(servers),
49 + tools: tools,
50 });
51
52 // 5. Execute the OpenAI-specific agent.
ts/examples/openai/src/agents-api/experiment.tool-router.ts new
+59
@@ -0,0 +1,59 @@
1 +import { Composio } from '@composio/core';
2 +import { OpenAIAgentsProvider } from '@composio/openai-agents';
3 +import { hostedMcpTool, Agent as OpenAIAgent, run } from '@openai/agents';
4 +import type { HostedMCPTool } from '@openai/agents';
5 +import 'dotenv/config';
6 +
7 +// 1. Initialize Composio.
8 +const composio = new Composio({
9 + apiKey: process.env.COMPOSIO_API_KEY,
10 + provider: new OpenAIAgentsProvider(),
11 + allowTracking: false,
12 +});
13 +
14 +const externalUserId = 'default';
15 +
16 +// 2. Create an tool router session
17 +const mcpSession = await composio.experimental.toolRouter.createSession(externalUserId, {
18 + toolkits: ["gmail", "github"],
19 +});
20 +
21 +// 3. Retrieve the MCP server instance for the tool router
22 +
23 +const tools: HostedMCPTool[] = [
24 + hostedMcpTool({
25 + serverLabel: 'composio tool router',
26 + serverUrl: mcpSession.url,
27 + requireApproval: {
28 + never: {
29 + toolNames: ['GMAIL_FETCH_EMAILS'],
30 + },
31 + },
32 + }),
33 +];
34 +
35 +// 4. Pass tools to OpenAI-specific Agent.
36 +const agent = new OpenAIAgent({
37 + name: 'Gmail Assistant',
38 + instructions: `
39 + You are a helpful Gmail assistant that fetches and summarizes emails.
40 + When fetching emails, provide a clear summary of the results including sender, subject, and date.
41 + Be concise and provide actionable information based on the email content.
42 + `,
43 + model: 'gpt-4o-mini',
44 + tools: tools,
45 +});
46 +
47 +// 5. Execute the OpenAI-specific agent.
48 +// Fetch and summarize recent emails
49 +console.log('\n=== Fetching and Summarizing Recent Emails ===');
50 +const emailResponse = await run(
51 + agent,
52 + 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
53 +);
54 +console.log('\n📬 Email Summary:');
55 +
56 +const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);
57 +
58 +// @ts-ignore
59 +console.log(output?.content[0].text);
ts/examples/openai/src/experiment.mcp.ts deleted
-124
@@ -1,124 +0,0 @@
1 -import { Composio } from '@composio/core';
2 -import OpenAI from 'openai';
3 -import { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';
4 -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
5 -import 'dotenv/config';
6 -
7 -function sanitizeString(input: string): string {
8 - return input.replace(/[^a-zA-Z0-9_-]+/g, '-');
9 -}
10 -
11 -async function wrapTools(client: MCPClient): Promise<Array<OpenAI.ChatCompletionFunctionTool>> {
12 - async function* listAllTools(client: MCPClient, maxTools = 128) {
13 - let cursor: string | undefined = undefined;
14 - let numTools = 0;
15 - while (numTools < maxTools) {
16 - const t = await client.listTools({cursor});
17 - for (const tool of t.tools) {
18 - yield tool;
19 - numTools++;
20 - }
21 - if (!t.nextCursor) {
22 - break;
23 - }
24 - cursor = t.nextCursor;
25 - }
26 - }
27 -
28 - const tools = await Array.fromAsync(listAllTools(client));
29 -
30 - return tools.map(tool => {
31 - return {
32 - type: 'function',
33 - function: {
34 - name: sanitizeString(tool.name),
35 - description: tool.description!,
36 - parameters: tool.inputSchema,
37 - strict: false,
38 - }
39 - }
40 - })
41 -}
42 -
43 -// 1. Initialize Composio.
44 -const composio = new Composio({
45 - apiKey: process.env.COMPOSIO_API_KEY,
46 -});
47 -
48 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
49 -const externalUserId = '<external_user_id>'; // Replace it with the user id
50 -const allowedTools = ['GMAIL_FETCH_EMAILS'];
51 -
52 -// 2. Create an MCP config
53 -const mcpConfig = await composio.experimental.mcpConfig.create(
54 - `gmail-mcp-${Date.now()}`,
55 - [
56 - {
57 - authConfigId,
58 - allowedTools,
59 - },
60 - ],
61 - { isChatAuth: true }
62 -);
63 -
64 -// 3. Retrieve the MCP server instance for the connected accounts
65 -const url = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
66 - limitTools: allowedTools,
67 -});
68 -
69 -// 4. Create a generic MCP client.
70 -// This client needs to remain "alive" not be dropped by the GC until
71 -// the tools are retrieved from it.
72 -const serverParams = new SSEClientTransport(url);
73 -const mcpClient = new MCPClient({
74 - name: 'composio-mcp-client',
75 - version: '1.0.0',
76 -});
77 -
78 -// 5. Retrieve tools.
79 -await mcpClient.connect(serverParams);
80 -const tools = await wrapTools(mcpClient);
81 -console.dir(tools, { depth: null });
82 -console.log(`✅ Tools available: ${tools.map(t => t.function.name).join(', ')}\n`);
83 -
84 -// 6. Pass tools to OpenAI-specific Agent.
85 -const openai = new OpenAI();
86 -const response = await openai.chat.completions.create({
87 - model: 'gpt-4o-mini',
88 - messages: [
89 - {
90 - role: 'system',
91 - content: `
92 - You are a helpful Gmail assistant that fetches and summarizes emails.
93 - When fetching emails, provide a clear summary of the results including sender, subject, and date.
94 - Be concise and provide actionable information based on the email content.
95 - `,
96 - },
97 - {
98 - role: 'user',
99 - content: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,
100 - }
101 - ],
102 - tools,
103 - tool_choice: 'auto',
104 -});
105 -
106 -/**
107 - * If the assistant has tool calls, execute them and log the result
108 - */
109 -if (
110 - response.choices[0].message.tool_calls &&
111 - response.choices[0].message.tool_calls[0].type === 'function'
112 -) {
113 - console.log(JSON.stringify(response, null, 2));
114 - const toolCall = response.choices[0].message.tool_calls[0];
115 - if (toolCall.type === 'function') {
116 - console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);
117 - }
118 - const result = await composio.provider.handleToolCalls('default', response);
119 - console.log(result);
120 -}
121 -
122 -await mcpClient.close();
123 -
124 -console.log('\n✅ OpenAI MCP Example completed successfully!');
ts/examples/openai/src/responses-api/experiment.mcp.ts
+23 -27
@@ -3,27 +3,11 @@ import { OpenAIResponsesProvider } from '@composio/openai';
3 import OpenAI from 'openai';
4 import 'dotenv/config';
5
6 -function sanitizeString(input: string): string {
7 - return input.replace(/[^a-zA-Z0-9_-]+/g, '-');
8 -}
9 -
10 -function wrapTools(servers: Array<OpenAI.Responses.Tool.Mcp>): Array<OpenAI.Responses.Tool.Mcp> {
11 - return servers.map(server => {
12 - const { server_label, ...rest } = server;
13 - return {
14 - ...rest,
15 - /**
16 - * 'server_label' must start with a letter and consist of only letters, digits, '-' and '_'
17 - */
18 - server_label: sanitizeString(server_label),
19 - };
20 - });
21 -}
22 -
6 // 1. Initialize Composio.
7 const composio = new Composio({
8 apiKey: process.env.COMPOSIO_API_KEY,
9 provider: new OpenAIResponsesProvider(),
10 + allowTracking: false,
11 });
12
13 const authConfigId = '<auth_config_id>'; // Use your auth config ID
@@ -31,21 +15,28 @@ const externalUserId = '<external_user_id>'; // Replace it with the user id from
15 const allowedTools = ['GMAIL_FETCH_EMAILS'];
16
17 // 2. Create an MCP config
34 -const mcpConfig = await composio.experimental.mcpConfig.create(
35 - `gmail-mcp-${Date.now()}`,
36 - [
18 +const mcpConfig = await composio.mcp.create(`gmail-mcp-${Date.now()}`, {
19 + toolkits: [
20 {
21 + toolkit: 'gmail',
22 authConfigId,
39 - allowedTools,
23 },
24 ],
42 - { isChatAuth: true }
43 -);
25 + allowedTools,
26 + manuallyManageConnections: true,
27 +});
28
29 // 3. Retrieve the MCP server instance for the connected accounts
46 -const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
47 - limitTools: allowedTools,
48 -});
30 +const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
31 +
32 +const tools = [
33 + {
34 + type: 'mcp' as const,
35 + server_label: mcp.name,
36 + server_url: mcp.url,
37 + },
38 +];
39 +console.log({ tools });
40
41 // 4. Pass tools to OpenAI-specific Agent.
42 const openai = new OpenAI();
@@ -57,9 +48,14 @@ const emailResponse = await openai.responses.create({
48 Be concise and provide actionable information based on the email content.
49 `,
50 input: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,
60 - tools: wrapTools(servers),
51 + tools: tools,
52 });
53
54 +console.log(JSON.stringify(emailResponse, null, 2));
55 +
56 +const result = await composio.provider.handleToolCalls('default', emailResponse.output);
57 +console.log({ result });
58 +
59 const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);
60
61 console.log(
ts/examples/vercel/src/experimental.mcp.ts
+8 -11
@@ -16,24 +16,21 @@ const externalUserId = '<extern_user_id>'; // Replace it with the user id
16 const allowedTools = ['GMAIL_FETCH_EMAILS'];
17
18 // 2. Create an MCP config
19 -const mcpConfig = await composio.experimental.mcpConfig.create(
20 - `${Date.now()}`,
21 - [
19 +const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
20 + toolkits: [
21 {
23 - // https://platform.composio.dev/alberto_schiabel/2025-09-12/auth-configs/ac_ydsgH6ZRO1Xc
22 + toolkit: 'gmail',
23 authConfigId,
25 - allowedTools,
24 },
25 ],
28 - { isChatAuth: true }
29 -);
26 + allowedTools,
27 + manuallyManageConnections: false,
28 +});
29
30 // 3. Retrieve the MCP server instance for the user
32 -const url = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
33 - limitTools: allowedTools,
34 -});
31 +const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
32
36 -const serverParams = new SSEClientTransport(url);
33 +const serverParams = new SSEClientTransport(new URL(server.url));
34
35 const mcpClient = await createMCPClient({
36 name: 'composio-mcp-client',
ts/examples/vercel/src/experimental.tool-router.ts new
+59
@@ -0,0 +1,59 @@
1 +import { openai } from '@ai-sdk/openai';
2 +import { Composio } from '@composio/core';
3 +import { VercelProvider } from '@composio/vercel';
4 +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
5 +import { experimental_createMCPClient as createMCPClient, stepCountIs, streamText } from 'ai';
6 +import 'dotenv/config';
7 +
8 +// 1. Initialize Composio.
9 +const composio = new Composio({
10 + apiKey: process.env.COMPOSIO_API_KEY,
11 + provider: new VercelProvider(),
12 +});
13 +
14 +// 2. Create an MCP session
15 +console.log('🔄 Creating toolrouter session...');
16 +const mcp = await composio.experimental.toolRouter.createSession('default', {
17 + toolkits: ['gmail', 'hackernews', 'github'],
18 +});
19 +
20 +console.log(JSON.stringify(mcp, null, 2));
21 +
22 +
23 +console.log(`✅ Toolrouter session created: ${mcp.sessionId}`);
24 +console.log(`🔄 Connecting to MCP Server: ${mcp.url}`);
25 +
26 +const serverParams = new StreamableHTTPClientTransport(new URL(mcp.url));
27 +
28 +const mcpClient = await createMCPClient({
29 + name: 'composio-mcp-client',
30 + transport: serverParams,
31 +});
32 +
33 +// 5. Retrieve tools.
34 +console.log(`🔄 Retrieving tools...`);
35 +const tools = await mcpClient.tools();
36 +console.log(`✅ Tools Retrieved`);
37 +Object.keys(tools).map(tool => console.log(` 📦 ${tool}`));
38 +
39 +// 6. Pass tools to Vercel-specific Agent.
40 +console.log(`🔄 Executing agent...`);
41 +const stream = streamText({
42 + model: openai('gpt-4o-mini'),
43 + messages: [
44 + {
45 + role: 'user',
46 + content: `What's latest on hackernews?`,
47 + },
48 + ],
49 + stopWhen: stepCountIs(5),
50 + tools,
51 +});
52 +console.log(`🤖 Agent Response:`);
53 +// 7. Execute the Vercel AI-specific Agent.
54 +for await (const textPart of stream.textStream) {
55 + process.stdout.write(textPart);
56 +}
57 +
58 +// 8. Close Vercel AI's MCP client.
59 +await mcpClient.close();
ts/packages/core/src/composio.ts
+32 -18
@@ -5,7 +5,8 @@ import { Toolkits } from './models/Toolkits';
5 import { Triggers } from './models/Triggers';
6 import { AuthConfigs } from './models/AuthConfigs';
7 import { ConnectedAccounts } from './models/ConnectedAccounts';
8 -import { ExperimentalMCP, MCP } from './models/MCP';
8 +import { MCP } from './models/MCP.experimental';
9 +import { MCP as DeprecatedMCP } from './models/MCP';
10 import { telemetry } from './telemetry/Telemetry';
11 import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';
12 import logger from './utils/logger';
@@ -17,15 +18,10 @@ import type { ComposioRequestHeaders } from './types/composio.types';
18 import { Files } from './models/Files';
19 import { getDefaultHeaders } from './utils/session';
20 import { ToolkitVersionParam } from './types/tool.types';
20 -import { MCPConfig } from './models/MCPConfig';
21 +import { ToolRouter } from './models/ToolRouter.experimental';
22
23 export type ComposioConfig<
23 - TProvider extends BaseComposioProvider<
24 - unknown,
25 - unknown,
26 - /* TMcpResponse */ unknown,
27 - /* TMcpExperimentalResponse */ unknown
28 - > = OpenAIProvider,
24 + TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
25 > = {
26 /**
27 * The API key for the Composio API.
@@ -95,7 +91,7 @@ export type ComposioConfig<
91 * It is used to initialize the Composio SDK and provide a global configuration.
92 */
93 export class Composio<
98 - TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown> = OpenAIProvider,
94 + TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
95 > {
96 /**
97 * The Composio API client.
@@ -117,19 +113,22 @@ export class Composio<
113 triggers: Triggers;
114 provider: TProvider;
115 files: Files;
120 - // auth configs
116 authConfigs: AuthConfigs;
122 - // connected accounts
117 connectedAccounts: ConnectedAccounts;
124 -
125 - mcp: MCP<TProvider>;
118 + mcp: MCP;
119
120 /**
121 * Experimental features
122 */
123 experimental: {
131 - mcp: ExperimentalMCP<TProvider>;
132 - mcpConfig: MCPConfig<TProvider>;
124 + toolRouter: ToolRouter;
125 + };
126 +
127 + /**
128 + * Deprecated features
129 + */
130 + deprecated: {
131 + mcp: DeprecatedMCP<TProvider>;
132 };
133
134 /**
@@ -204,7 +203,7 @@ export class Composio<
203 });
204
205 this.tools = new Tools(this.client, this.provider, this.config);
207 - this.mcp = new MCP(this.client, this.provider);
206 + this.mcp = new MCP(this.client);
207 this.toolkits = new Toolkits(this.client);
208 this.triggers = new Triggers(this.client);
209 this.authConfigs = new AuthConfigs(this.client);
@@ -215,8 +214,23 @@ export class Composio<
214 * Initialize Experimental features
215 */
216 this.experimental = {
218 - mcp: new ExperimentalMCP(this.client, this.provider),
219 - mcpConfig: new MCPConfig(this.mcp),
217 + /**
218 + * Experimental tool router
219 + * Helps you create a single MCP server containing all the tools with smart routing.
220 + *
221 + * @description Allows you to create an isolated toolRouter MCP session for a user
222 + */
223 + toolRouter: new ToolRouter(this.client),
224 + };
225 +
226 + /**
227 + * Initialize Deprecated features
228 + */
229 + this.deprecated = {
230 + /**
231 + * @deprecated this feature will be removed soon, use `composio.mcp`
232 + */
233 + mcp: new DeprecatedMCP(this.client, this.provider),
234 };
235
236 /**
ts/packages/core/src/models/MCP.experimental.ts new
+430
@@ -0,0 +1,430 @@
1 +import { Composio as ComposioClient } from '@composio/client';
2 +import { telemetry } from '../telemetry/Telemetry';
3 +import {
4 + MCPConfigCreationParams,
5 + MCPConfigCreationParamsSchema,
6 + MCPConfigCreateResponse,
7 + MCPConfigResponseSchema,
8 + MCPServerInstance,
9 + MCPGetInstanceParams,
10 + MCPGetInstanceParamsSchema,
11 + MCPListResponse,
12 + MCPListParams,
13 + MCPListParamsSchema,
14 + MCPListResponseSchema,
15 + MCPItemSchema,
16 + MCPItem,
17 + MCPUpdateParams,
18 + MCPUpdateParamsSchema,
19 +} from '../types/mcp.experimental.types';
20 +import { MCPServerInstanceSchema } from '../types/mcp.experimental.types';
21 +import { ValidationError } from '../errors/ValidationErrors';
22 +import { transform } from '../utils/transform';
23 +import { McpUpdateResponse } from '@composio/client/resources.js';
24 +import { McpRetrieveResponse } from '@composio/client/resources';
25 +
26 +function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
27 + return transform(response)
28 + .with(MCPItemSchema)
29 + .using(raw => ({
30 + name: raw.name,
31 + allowedTools: raw.allowed_tools,
32 + id: raw.id,
33 + authConfigIds: raw.auth_config_ids,
34 + commands: raw.commands,
35 + MCPUrl: raw.mcp_url,
36 + toolkitIcons: raw.toolkit_icons,
37 + serverInstanceCount: raw.server_instance_count,
38 + toolkits: raw.toolkits,
39 + }));
40 +}
41 +/**
42 + * MCP (Model Control Protocol) class
43 + * Handles MCP server operations.
44 + * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
45 + */
46 +export class MCP {
47 + client: ComposioClient;
48 +
49 + constructor(client: ComposioClient) {
50 + this.client = client;
51 + telemetry.instrument(this);
52 + }
53 +
54 + /**
55 + * Create a new MCP configuration.
56 + * @param {Object} params - Parameters for creating the MCP configuration
57 + * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
58 + * @param {Object} params.options - Configuration options
59 + * @param {string} params.options.name - Unique name for the MCP configuration
60 + * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts
61 + * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
62 + *
63 + * @example
64 + * ```typescript
65 + * const server = await composio.mcpConfig.create("personal-mcp-server", {
66 + * toolkits: ["github", "slack"],
67 + * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
68 + * manuallyManageConnections: false
69 + * }
70 + * });
71 + *
72 + * const server = await composio.mcpConfig.create("personal-mcp-server", {
73 + * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }],
74 + * allowedTools: ["GMAIL_FETCH_EMAILS"],
75 + * manuallyManageConnections: false
76 + * }
77 + * });
78 + * ```
79 + */
80 + async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
81 + const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
82 + if (config.error) {
83 + throw new ValidationError('Invalid parameters passed to create mcp config', {
84 + cause: config.error,
85 + });
86 + }
87 +
88 + const toolkits: string[] = [];
89 + const auth_config_ids: string[] = [];
90 + const custom_tools: string[] = config.data.allowedTools ?? [];
91 +
92 + // extract all the toolkits, authconfigs, and allowed tools to separate slugs
93 + config.data.toolkits.forEach(toolkit => {
94 + if (typeof toolkit === 'string') {
95 + toolkits.push(toolkit);
96 + } else if (toolkit.toolkit) {
97 + toolkits.push(toolkit.toolkit);
98 + } else if (toolkit.authConfigId) {
99 + auth_config_ids.push(toolkit.authConfigId);
100 + }
101 + });
102 +
103 + const server = await this.client.mcp.custom.create({
104 + name,
105 + toolkits,
106 + auth_config_ids,
107 + custom_tools,
108 + // if manually manage account is set to true, disable composio account management tools
109 + managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
110 + });
111 +
112 + const camelCaseServer = transform(server)
113 + .with(MCPConfigResponseSchema)
114 + .using(raw => ({
115 + name: raw.name,
116 + allowedTools: raw.allowed_tools,
117 + id: raw.id,
118 + authConfigIds: raw.auth_config_ids,
119 + commands: raw.commands,
120 + MCPUrl: raw.mcp_url,
121 + }));
122 +
123 + return {
124 + ...camelCaseServer,
125 + generate: async (userId: string): Promise<MCPServerInstance> => {
126 + return await this.generate(userId, server.id, {
127 + manuallyManageConnections: config.data.manuallyManageConnections,
128 + });
129 + },
130 + };
131 + }
132 +
133 + /**
134 + * List the MCP servers with optional filtering and pagination
135 + * @param {Object} options - Filtering and pagination options
136 + * @param {number} [options.page=1] - Page number for pagination (1-based)
137 + * @param {number} [options.limit=10] - Maximum number of items to return per page
138 + * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
139 + * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
140 + * @param {string} [options.name] - Filter by MCP server name (partial match)
141 + * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
142 + *
143 + * @example
144 + * ```typescript
145 + * // List all MCP servers
146 + * const allServers = await composio.experimental.mcp.list({});
147 + *
148 + * // List with pagination
149 + * const pagedServers = await composio.experimental.mcp.list({
150 + * page: 2,
151 + * limit: 5
152 + * });
153 + *
154 + * // Filter by toolkit
155 + * const githubServers = await composio.experimental.mcp.list({
156 + * toolkits: ['github', 'slack']
157 + * });
158 + *
159 + * // Filter by name
160 + * const namedServers = await composio.experimental.mcp.list({
161 + * name: 'personal'
162 + * });
163 + * ```
164 + */
165 + async list(options: MCPListParams): Promise<MCPListResponse> {
166 + const { data: params, error } = MCPListParamsSchema.safeParse(options);
167 + if (error) {
168 + throw new ValidationError('Failed to validate list options', {
169 + cause: error,
170 + });
171 + }
172 +
173 + const listResponse = await this.client.mcp.list({
174 + page_no: params.page,
175 + limit: params.limit,
176 + toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
177 + auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
178 + name: params.name,
179 + });
180 +
181 + const transformedListResponse = transform(listResponse)
182 + .with(MCPListResponseSchema)
183 + .using(raw => ({
184 + currentPage: raw.current_page,
185 + totalPages: raw.total_pages,
186 + items: raw.items.map(item => ({
187 + name: item.name,
188 + allowedTools: item.allowed_tools,
189 + id: item.id,
190 + authConfigIds: item.auth_config_ids,
191 + commands: item.commands,
192 + MCPUrl: item.mcp_url,
193 + toolkitIcons: item.toolkit_icons,
194 + serverInstanceCount: item.server_instance_count,
195 + toolkits: item.toolkits,
196 + })),
197 + }));
198 +
199 + return transformedListResponse;
200 + }
201 +
202 + /**
203 + * Retrieve detailed information about a specific MCP server by its ID
204 + * @param {string} serverId - The unique identifier of the MCP server to retrieve
205 + * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
206 + *
207 + * @example
208 + * ```typescript
209 + * // Get a specific MCP server by ID
210 + * const server = await composio.experimental.mcp.get("mcp_12345");
211 + *
212 + * console.log(server.name); // "My Personal MCP Server"
213 + * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
214 + * console.log(server.toolkits); // ["github", "slack"]
215 + * console.log(server.serverInstanceCount); // 3
216 + *
217 + * // Access setup commands for different clients
218 + * console.log(server.commands.claude); // Claude setup command
219 + * console.log(server.commands.cursor); // Cursor setup command
220 + * console.log(server.commands.windsurf); // Windsurf setup command
221 + *
222 + * // Use the MCP URL for direct connections
223 + * const mcpUrl = server.MCPUrl;
224 + * ```
225 + *
226 + * @throws {ValidationError} When the server ID is invalid or server not found
227 + */
228 + async get(serverId: string): Promise<MCPItem> {
229 + const response = await this.client.mcp.retrieve(serverId);
230 + return transformMCPItemResponse(response);
231 + }
232 +
233 + /**
234 + * Delete an MCP server configuration permanently
235 + * @param {string} serverId - The unique identifier of the MCP server to delete
236 + * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
237 + *
238 + * @example
239 + * ```typescript
240 + * // Delete an MCP server by ID
241 + * const result = await composio.experimental.mcp.delete("mcp_12345");
242 + *
243 + * if (result.deleted) {
244 + * console.log(`Server ${result.id} has been successfully deleted`);
245 + * } else {
246 + * console.log(`Failed to delete server ${result.id}`);
247 + * }
248 + *
249 + * // Example with error handling
250 + * try {
251 + * const result = await composio.experimental.mcp.delete("mcp_12345");
252 + * console.log("Deletion successful:", result);
253 + * } catch (error) {
254 + * console.error("Failed to delete MCP server:", error.message);
255 + * }
256 + *
257 + * // Delete and verify from list
258 + * await composio.experimental.mcp.delete("mcp_12345");
259 + * const servers = await composio.experimental.mcp.list({});
260 + * const serverExists = servers.items.some(server => server.id === "mcp_12345");
261 + * console.log("Server still exists:", serverExists); // Should be false
262 + * ```
263 + *
264 + * @throws {ValidationError} When the server ID is invalid or server not found
265 + * @throws {Error} When the server cannot be deleted due to active connections or other constraints
266 + *
267 + * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
268 + */
269 + async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
270 + return await this.client.mcp.delete(serverId);
271 + }
272 +
273 + /**
274 + * Update an existing MCP server configuration with new settings
275 + * @param {string} serverId - The unique identifier of the MCP server to update
276 + * @param {Object} config - Update configuration parameters
277 + * @param {string} [config.name] - New name for the MCP server
278 + * @param {Array} [config.toolkits] - Updated toolkit configurations
279 + * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
280 + * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
281 + * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
282 + * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
283 + * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
284 + *
285 + * @example
286 + * ```typescript
287 + * // Update server name only
288 + * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
289 + * name: "My Updated MCP Server"
290 + * });
291 + *
292 + * // Update toolkits and tools
293 + * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
294 + * toolkits: [
295 + * {
296 + * toolkit: "github",
297 + * authConfigId: "auth_abc123",
298 + * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
299 + * },
300 + * {
301 + * toolkit: "slack",
302 + * authConfigId: "auth_xyz789",
303 + * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
304 + * }
305 + * ]
306 + * });
307 + *
308 + * // Update connection management setting
309 + * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
310 + * name: "Manual Auth Server",
311 + * manuallyManageConnections: true
312 + * });
313 + *
314 + * // Complete update example
315 + * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
316 + * name: "Production MCP Server",
317 + * toolkits: [
318 + * {
319 + * toolkit: "gmail",
320 + * authConfigId: "auth_gmail_prod",
321 + * }
322 + * ],
323 + * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
324 + * manuallyManageConnections: false
325 + * });
326 + *
327 + * console.log("Updated server:", fullyUpdatedServer.name);
328 + * console.log("New tools:", fullyUpdatedServer.allowedTools);
329 + * ```
330 + *
331 + * @throws {ValidationError} When the update parameters are invalid or malformed
332 + * @throws {Error} When the server ID doesn't exist or update fails
333 + *
334 + * @note Only provided fields will be updated. Omitted fields will retain their current values.
335 + * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
336 + */
337 + async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
338 + const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
339 + if (error) {
340 + throw new ValidationError('Failed to validate update params', {
341 + cause: error,
342 + });
343 + }
344 +
345 + const toolkits: string[] = [];
346 + const auth_config_ids: string[] = [];
347 + const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
348 +
349 + // extract all the toolkits, authconfigs, and allowed tools to separate slugs
350 + params.toolkits?.forEach(toolkit => {
351 + if (typeof toolkit === 'string') {
352 + toolkits.push(toolkit);
353 + } else if (toolkit.toolkit) {
354 + toolkits.push(toolkit.toolkit);
355 + } else if (toolkit.authConfigId) {
356 + auth_config_ids.push(toolkit.authConfigId);
357 + }
358 + });
359 + const response = await this.client.mcp.update(serverId, {
360 + ...{ name: params.name ?? undefined },
361 + ...(params.toolkits
362 + ? {
363 + custom_tools: custom_tools,
364 + toolkits: toolkits,
365 + auth_config_ids: auth_config_ids,
366 + }
367 + : {}),
368 + ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
369 + });
370 + return transformMCPItemResponse(response);
371 + }
372 +
373 + /**
374 + * Get server URLs for an existing MCP server.
375 + * The response is wrapped according to the provider's specifications.
376 + *
377 + * @example
378 + * ```typescript
379 + * import { Composio } from "@composio/code";
380 + *
381 + * const composio = new Composio();
382 + * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
383 + * ```
384 + *
385 + * @param userId {string} external user id from your database for whom you want the server for
386 + * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
387 + * @param options {object} additional options
388 + * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
389 + */
390 + async generate(
391 + userId: string,
392 + mcpConfigId: string,
393 + options?: MCPGetInstanceParams
394 + ): Promise<MCPServerInstance> {
395 + const server = await this.client.mcp.retrieve(mcpConfigId);
396 + const params = MCPGetInstanceParamsSchema.safeParse(
397 + options ?? { manuallyManageConnections: false }
398 + );
399 + if (params.error) {
400 + throw new ValidationError('Invalid params passed for Get Instance Params', {
401 + cause: params.error,
402 + });
403 + }
404 +
405 + const urlResponse = await this.client.mcp.generate.url({
406 + mcp_server_id: mcpConfigId,
407 + user_ids: [userId],
408 + managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
409 + });
410 +
411 + const userIdsURL = urlResponse.user_ids_url[0];
412 + const serverInstance = MCPServerInstanceSchema.safeParse({
413 + id: server.id,
414 + name: server.name,
415 + type: 'streamable_http' as const,
416 + url: userIdsURL,
417 + userId: userId,
418 + allowedTools: server.allowed_tools,
419 + authConfigs: server.auth_config_ids,
420 + });
421 +
422 + if (serverInstance.error) {
423 + throw new ValidationError('Failed to parse MCP server instance', {
424 + cause: serverInstance.error,
425 + });
426 + }
427 +
428 + return serverInstance.data;
429 + }
430 +}
ts/packages/core/src/models/MCP.ts
+3 -89
@@ -51,23 +51,15 @@ import { ConnectionRequest } from '../types/connectionRequest.types';
51 * Extract the MCP response type from a provider.
52 */
53 type ExtractMcpResponseType<T> =
54 - T extends BaseComposioProvider<unknown, unknown, infer TMcp, unknown>
54 + T extends BaseComposioProvider<unknown, unknown, infer TMcp>
55 ? TMcp
56 : /* @default */ McpServerGetResponse;
57
58 -/**
59 - * Extract the experimental MCP response type from a provider.
60 - */
61 -type ExtractExperimentalMcpResponseType<T> =
62 - T extends BaseComposioProvider<unknown, unknown, unknown, infer TMcpExperimental>
63 - ? TMcpExperimental
64 - : /* @default */ McpServerGetResponse;
65 -
58 /**
59 * MCP (Model Control Protocol) class
60 * Handles MCP server operations
61 */
70 -export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown>> {
62 +export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown>> {
63 private client: ComposioClient;
64 private toolkits: Toolkits;
65 protected provider: TProvider;
@@ -775,6 +767,7 @@ export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknow
767 * @param serverName - Name of the MCP server
768
769 * @returns Transformed response in appropriate format
770 + * @deprecated
771 */
772 private wrapMcpServerResponse(
773 data: McpUrlResponseCamelCase,
@@ -885,82 +878,3 @@ export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknow
878 return this.get(servers[0].id);
879 }
880 }
888 -
889 -/**
890 - * MCP (Model Control Protocol) class
891 - * Handles MCP server operations.
892 - * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
893 - */
894 -export class ExperimentalMCP<
895 - TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown>,
896 -> {
897 - mcp: MCP<TProvider>;
898 - provider: TProvider;
899 - declare readonly TMcpExperimentalResponse: ExtractExperimentalMcpResponseType<TProvider>;
900 -
901 - constructor(client: ComposioClient, provider: TProvider) {
902 - this.mcp = new MCP(client, provider);
903 - this.provider = provider;
904 - telemetry.instrument(this);
905 - }
906 -
907 - /**
908 - * Get server URLs for an existing MCP server.
909 - * The response is wrapped according to the provider's specifications.
910 - *
911 - * @example
912 - * ```typescript
913 - * import { Composio } from "@composio/code";
914 - *
915 - * const composio = new Composio();
916 - * const server = await composio.experimental.mcp.getServer("default", "<mcp_config_id>");
917 - * ```
918 - *
919 - * @param userId {string} external user id from your database for whom you want the server for
920 - * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
921 - * @param options {object} additional options
922 - * @param options.limitTools {string[]} limit the tools to the ones specified
923 - * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
924 - */
925 - async getServer(
926 - userId: string,
927 - mcpConfigId: string,
928 - options?: {
929 - limitTools?: string[];
930 - isChatAuth?: boolean;
931 - }
932 - ): Promise<ReturnType<TProvider['wrapMcpServers']>> {
933 - return this.mcp.getServer(mcpConfigId, userId, options).then(res => {
934 - // TODO: investigate why this cast is needed in the first place.
935 - // Without it, this type is always inferred as `unknown`.
936 - return this.provider.wrapMcpServers(res) as ReturnType<TProvider['wrapMcpServers']>;
937 - });
938 - }
939 -
940 - /**
941 - * Get server URLs for an existing MCP server.
942 - *
943 - * @example
944 - * ```typescript
945 - * import { Composio } from "@composio/code";
946 - *
947 - * const composio = new Composio();
948 - * const server = await composio.experimental.mcp.getRawMCPServer("default", "<mcp_config_id>");
949 - * ```
950 - *
951 - * @param userId {string} external user id from your database for whom you want the server for
952 - * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
953 - * @param options.limitTools {string[]} limit the tools to the ones specified
954 - * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
955 - */
956 - async getRawMCPServer(
957 - userId: string,
958 - mcpConfigId: string,
959 - options?: {
960 - limitTools?: string[];
961 - isChatAuth?: boolean;
962 - }
963 - ) {
964 - return await this.getServer(mcpConfigId, userId, options);
965 - }
966 -}
ts/packages/core/src/models/MCPConfig.ts deleted
-80
@@ -1,80 +0,0 @@
1 -import type { BaseComposioProvider } from '../provider/BaseProvider';
2 -import { telemetry } from '../telemetry/Telemetry';
3 -import type { McpServerCreateResponse, McpRetrieveResponse } from '../types/mcp.types';
4 -import type { MCP } from './MCP';
5 -
6 -/**
7 - * MCPConfig (Model Control Protocol Config) class
8 - * Handles CRUD operations related to MCP configurations.
9 - */
10 -export class MCPConfig<TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown>> {
11 - constructor(private mcp: MCP<TProvider>) {
12 - telemetry.instrument(this);
13 - }
14 -
15 - /**
16 - * Create a new MCP configuration.
17 - * @param {Object} params - Parameters for creating the MCP configuration
18 - * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
19 - * @param {Object} params.options - Configuration options
20 - * @param {string} params.options.name - Unique name for the MCP configuration
21 - * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
22 - * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
23 - *
24 - * @example
25 - * ```typescript
26 - * const server = await composio.mcpConfig.create("personal-mcp-server", [
27 - * {
28 - * authConfigId: "ac_xyz",
29 - * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
30 - * }
31 - * ],
32 - * {
33 - * isChatAuth: true
34 - * }
35 - * });
36 - * ```
37 - */
38 - async create(
39 - name: string,
40 - serverConfig: Array<{
41 - authConfigId: string;
42 - allowedTools: string[];
43 - }>,
44 - options: {
45 - isChatAuth?: boolean;
46 - }
47 - ): Promise<McpServerCreateResponse<typeof this.mcp.TMcpResponse>> {
48 - return this.mcp.create(name, serverConfig, options);
49 - }
50 -
51 - /**
52 - * Get details of a specific MCP config by name
53 - * @param {string} configName - Config name
54 - * @returns {Promise<McpRetrieveResponse>} Server details
55 - * @throws {ValidationError} If no MCP Config found with the given name
56 - * @throws {ValidationError} If multiple MCP Configs found with the same name
57 - *
58 - * @example
59 - * ```typescript
60 - * const mcpConfig = await composio.mcpConfig.getByName('my-gmail-server');
61 - * ```
62 - */
63 - async getByName(configName: string): Promise<McpRetrieveResponse> {
64 - return this.mcp.getByName(configName);
65 - }
66 -
67 - /**
68 - * Get details of a specific MCP Config
69 - * @param {string} configId - Config UUID
70 - * @returns {Promise<McpRetrieveResponse>} Config details
71 - *
72 - * @example
73 - * ```typescript
74 - * const mcpConfig = await composio.mcpConfig.get('config-uuid');
75 - * ```
76 - */
77 - async get(configId: string): Promise<McpRetrieveResponse> {
78 - return this.mcp.get(configId);
79 - }
80 -}
ts/packages/core/src/models/ToolRouter.experimental.ts new
+75
@@ -0,0 +1,75 @@
1 +import { Composio as ComposioClient } from '@composio/client';
2 +import { telemetry } from '../telemetry/Telemetry';
3 +import {
4 + ToolRouterConfig,
5 + ToolRouterConfigSchema,
6 + ToolRouterSession,
7 + ToolRouterSessionSchema,
8 +} from '../types/toolRouter.types';
9 +import { ValidationError } from '../errors';
10 +import { transform } from '../utils/transform';
11 +
12 +export class ToolRouter {
13 + constructor(private client: ComposioClient) {
14 + this.client = client;
15 + telemetry.instrument(this);
16 + }
17 +
18 + /**
19 + * Creates a new Session for the tool router
20 + *
21 + * @param userId {string} The user id to create the session for
22 + * @param routerConfig {ToolRouterConfig} The router config to use
23 + * @returns {Promise<ToolRouterSession>} The tool router session
24 + *
25 + * @example
26 + * ```typescript
27 + * import { Composio } form "@composio/core"
28 + *
29 + * const composio = new Composio()
30 + * const userId = "xxx-ooo-xxxx"
31 + *
32 + * const mcpSession = await composio.experimental.toolRouter.createSession(userId, {
33 + * toolkits: ["github", "hackernews", "slack"]
34 + * })
35 + *
36 + * // with auth configs
37 + * const mcpSession = await composio.experimental.toolRouter.createSession(userId, {
38 + * toolkits: [{ toolkit: "github", authConfingId: "ac_123455344"}]
39 + * ```
40 + */
41 + async createSession(userId: string, routerConfig?: ToolRouterConfig): Promise<ToolRouterSession> {
42 + const config = ToolRouterConfigSchema.safeParse(routerConfig ?? {});
43 + if (config.error) {
44 + throw new ValidationError('Failed to parse tool router config', {
45 + cause: config.error,
46 + });
47 + }
48 +
49 + const toolkitConfig = config.data.toolkits?.map(config => {
50 + if (typeof config === 'string') {
51 + return { toolkit: config };
52 + } else {
53 + return {
54 + toolkit: config.toolkit,
55 + auth_config_id: config.authConfigId,
56 + };
57 + }
58 + });
59 +
60 + const session = await this.client.toolRouter.createSession({
61 + user_id: userId,
62 + config: {
63 + toolkits: toolkitConfig,
64 + manually_manage_connections: config.data.manuallyManageConnections,
65 + },
66 + });
67 +
68 + return transform(session)
69 + .with(ToolRouterSessionSchema)
70 + .using(raw => ({
71 + sessionId: raw.session_id,
72 + url: raw.chat_session_mcp_url,
73 + }));
74 + }
75 +}
ts/packages/core/src/models/Tools.ts
+1 -1
@@ -57,7 +57,7 @@ import { getToolkitVersion } from '../utils/toolkitVersion';
57 export class Tools<
58 TToolCollection,
59 TTool,
60 - TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown, unknown>,
60 + TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
61 > {
62 private client: ComposioClient;
63 private readonly customTools: CustomTools;
ts/packages/core/src/provider/BaseProvider.ts
+7 -23
@@ -9,10 +9,7 @@ import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
9 * Base class for all providers.
10 * This class is not meant to be used directly, but rather to be extended by different provider implementations.
11 */
12 -abstract class BaseProvider<
13 - TMcpResponse = McpServerGetResponse,
14 - TMcpExperimentalResponse = McpServerGetResponse,
15 -> {
12 +abstract class BaseProvider<TMcpResponse> {
13 /**
14 * @public
15 * The name of the provider.
@@ -73,12 +70,6 @@ abstract class BaseProvider<
70 * @returns Transformed response in provider-specific format, or undefined to use default transformation
71 */
72 wrapMcpServerResponse?(data: McpUrlResponse): TMcpResponse;
76 -
77 - /**
78 - * This method replaces `wrapMcpServerResponse` when Composio's config contains has the
79 - * `experimental.mcp` flag enabled.
80 - */
81 - abstract wrapMcpServers(data: TMcpResponse): TMcpExperimentalResponse;
73 }
74
75 /**
@@ -90,8 +81,7 @@ export abstract class BaseNonAgenticProvider<
81 TToolCollection,
82 TTool,
83 TMcpResponse = McpServerGetResponse,
93 - TMcpExperimentalResponse = McpServerGetResponse,
94 -> extends BaseProvider<TMcpResponse, TMcpExperimentalResponse> {
84 +> extends BaseProvider<TMcpResponse> {
85 override readonly _isAgentic = false;
86
87 /**
@@ -116,9 +106,8 @@ export abstract class BaseNonAgenticProvider<
106 export abstract class BaseAgenticProvider<
107 TToolCollection,
108 TTool,
119 - TMcpResponse = McpServerGetResponse,
120 - TMcpExperimentalResponse = McpServerGetResponse,
121 -> extends BaseProvider<TMcpResponse, TMcpExperimentalResponse> {
109 + TMcpResponse,
110 +> extends BaseProvider<TMcpResponse> {
111 override readonly _isAgentic = true;
112
113 /**
@@ -142,11 +131,6 @@ export abstract class BaseAgenticProvider<
131 * Base type for all providers.
132 * This type is used to infer the type of the provider from the provider implementation.
133 */
145 -export type BaseComposioProvider<
146 - TToolCollection,
147 - TTool,
148 - TMcpResponse = McpServerGetResponse,
149 - TMcpExperimentalResponse = McpServerGetResponse,
150 -> =
151 - | BaseNonAgenticProvider<TToolCollection, TTool, TMcpResponse, TMcpExperimentalResponse>
152 - | BaseAgenticProvider<TToolCollection, TTool, TMcpResponse, TMcpExperimentalResponse>;
134 +export type BaseComposioProvider<TToolCollection, TTool, TMcpResponse = McpServerGetResponse> =
135 + | BaseNonAgenticProvider<TToolCollection, TTool, TMcpResponse>
136 + | BaseAgenticProvider<TToolCollection, TTool, TMcpResponse>;
ts/packages/core/src/provider/ComposioProvider.ts
-4
@@ -19,10 +19,6 @@ export class ComposioProvider extends BaseNonAgenticProvider<Array<CustomTool>,
19 super();
20 }
21
22 - override wrapMcpServers(data: McpServerGetResponse) {
23 - return data;
24 - }
25 -
22 wrapTool = (tool: Tool): CustomTool => {
23 return tool as CustomTool;
24 };
ts/packages/core/src/provider/OpenAIProvider.ts
+3 -20
@@ -14,7 +14,7 @@ import { Tool, ToolExecuteParams } from '../types/tool.types';
14 import logger from '../utils/logger';
15 import { ExecuteToolModifiers } from '../types/modifiers.types';
16 import { ExecuteToolFnOptions } from '../types/provider.types';
17 -import { McpUrlResponse, McpServerGetResponse, McpServerUrlInfo } from '../types/mcp.types';
17 +import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
18
19 export type OpenAiTool = OpenAI.ChatCompletionTool;
20 export type OpenAiToolCollection = Array<OpenAiTool>;
@@ -22,8 +22,7 @@ export type OpenAiToolCollection = Array<OpenAiTool>;
22 export class OpenAIProvider extends BaseNonAgenticProvider<
23 OpenAiToolCollection,
24 OpenAiTool,
25 - McpServerGetResponse,
26 - URL
25 + McpServerGetResponse
26 > {
27 readonly name = 'openai';
28
@@ -58,29 +57,13 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
57 * @param data - The MCP URL response data
58 * @returns Standard MCP server response format
59 */
61 - wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
60 + override wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
61 return data.map(item => ({
62 url: new URL(item.url),
63 name: item.name,
64 }));
65 }
66
68 - override wrapMcpServers(servers: McpServerGetResponse): URL {
69 - function wrapMcpServer(server: McpServerUrlInfo) {
70 - return server.url;
71 - }
72 -
73 - if (Array.isArray(servers)) {
74 - if (servers.length === 0) {
75 - throw new Error('No servers found');
76 - }
77 -
78 - return wrapMcpServer(servers[0]);
79 - }
80 -
81 - return wrapMcpServer(servers);
82 - }
83 -
67 /**
68 * Wraps a Composio tool in the OpenAI function calling format.
69 *
ts/packages/core/src/types/authConfigs.types.ts
+2
@@ -17,6 +17,7 @@ export const AuthSchemeTypes = {
17 NO_AUTH: 'NO_AUTH',
18 BASIC_WITH_JWT: 'BASIC_WITH_JWT',
19 CALCOM_AUTH: 'CALCOM_AUTH',
20 + SERVICE_ACCOUNT: 'SERVICE_ACCOUNT',
21 } as const;
22 export type AuthSchemeType = (typeof AuthSchemeTypes)[keyof typeof AuthSchemeTypes];
23
@@ -40,6 +41,7 @@ export const AuthSchemeEnum = z.enum([
41 'NO_AUTH',
42 'BASIC_WITH_JWT',
43 'CALCOM_AUTH',
44 + 'SERVICE_ACCOUNT',
45 ]);
46 export const CreateCustomAuthConfigParamsSchema = z.object({
47 type: z.literal('use_custom_auth'),
ts/packages/core/src/types/mcp.experimental.types.ts new
+163
@@ -0,0 +1,163 @@
1 +import z from 'zod';
2 +
3 +export const MCPServerInstanceSchema = z.object({
4 + id: z.string(),
5 + name: z.string(),
6 + type: z.literal('streamable_http'),
7 + url: z.string(),
8 + userId: z.string(),
9 + allowedTools: z.array(z.string()),
10 + authConfigs: z.array(z.string()),
11 +});
12 +export type MCPServerInstance = z.infer<typeof MCPServerInstanceSchema>;
13 +
14 +/**
15 + * MCP Create Method Input Types
16 + */
17 +export const MCPConfigToolkitsSchema = z.object({
18 + toolkit: z.string().describe('Id of the toolkit').optional(),
19 + authConfigId: z.string().describe('Id of the auth config').optional(),
20 +});
21 +
22 +export const MCPConfigCreationParamsSchema = z.object({
23 + toolkits: z.array(z.union([MCPConfigToolkitsSchema, z.string()])),
24 + allowedTools: z.array(z.string()).optional(),
25 + manuallyManageConnections: z
26 + .boolean()
27 + .default(false)
28 + .optional()
29 + .describe(
30 + `Whether to manually manage accounts. If true, you need to manage accounts manually connect user accounts.
31 +If set to false, composio will inject account maangement tools into your mcp server for agents to request and authenticate accounts.
32 +defaults to false`
33 + ),
34 +});
35 +export type MCPConfigCreationParams = z.infer<typeof MCPConfigCreationParamsSchema>;
36 +
37 +export const MCPConfigResponseSchema = z.object({
38 + /**
39 + * Unique identifier for the newly created custom MCP server
40 + */
41 + id: z.string(),
42 +
43 + /**
44 + * Human-readable name of the custom MCP server
45 + */
46 + name: z.string(),
47 +
48 + /**
49 + * List of tool identifiers that are enabled for this server
50 + */
51 + allowedTools: z.array(z.string()),
52 +
53 + /**
54 + * ID references to the auth configurations used by this server
55 + */
56 + authConfigIds: z.array(z.string()),
57 +
58 + /**
59 + * Set of command line instructions for connecting various clients to this MCP server
60 + */
61 + commands: z.object({
62 + /**
63 + * Command line instruction for Claude client setup
64 + */
65 + claude: z.string(),
66 +
67 + /**
68 + * Command line instruction for Cursor client setup
69 + */
70 + cursor: z.string(),
71 +
72 + /**
73 + * Command line instruction for Windsurf client setup
74 + */
75 + windsurf: z.string(),
76 + }),
77 +
78 + /**
79 + * URL endpoint for establishing Server-Sent Events (SSE) connection to this MCP server
80 + */
81 + MCPUrl: z.string(),
82 +});
83 +
84 +export type MCPConfigResponse = z.infer<typeof MCPConfigResponseSchema>;
85 +export interface MCPConfigCreateResponse extends MCPConfigResponse {
86 + /**
87 + * Creates an instance for a user of the specific MCP Server/COnfig
88 + * @param userId {string}
89 + * @returns {MCPServerInstance}
90 + */
91 + generate: (userId: string) => Promise<MCPServerInstance>;
92 +}
93 +
94 +export const MCPGetInstanceParamsSchema = z.object({
95 + manuallyManageConnections: z
96 + .boolean()
97 + .default(false)
98 + .optional()
99 + .describe(
100 + `Whether to manually manage accounts. If true, you need to manage accounts manually connect user accounts.
101 +If set to false, composio will inject account maangement tools into your mcp server for agents to request and authenticate accounts.
102 +defaults to false`
103 + ),
104 +});
105 +export type MCPGetInstanceParams = z.infer<typeof MCPGetInstanceParamsSchema>;
106 +
107 +export const MCPListParamsSchema = z.object({
108 + page: z.number().optional().default(1),
109 + limit: z.number().optional().default(10),
110 + toolkits: z.array(z.string()).optional().default([]),
111 + authConfigs: z.array(z.string()).optional().default([]),
112 + name: z.string().optional(),
113 +});
114 +export type MCPListParams = z.infer<typeof MCPListParamsSchema>;
115 +
116 +export const MCPItemSchema = MCPConfigResponseSchema.extend({
117 + ...z.object({
118 + toolkitIcons: z.record(z.string(), z.string()),
119 + serverInstanceCount: z.number(),
120 + toolkits: z.array(z.string()),
121 + }).shape,
122 +});
123 +export type MCPItem = z.infer<typeof MCPItemSchema>;
124 +export const MCPListResponseSchema = z.object({
125 + items: z.array(MCPItemSchema),
126 + currentPage: z.number(),
127 + totalPages: z.number(),
128 +});
129 +export type MCPListResponse = z.infer<typeof MCPListResponseSchema>;
130 +
131 +export const MCPUpdateParamsSchema = z.object({
132 + name: z.string().optional(),
133 + toolkits: z.array(z.union([MCPConfigToolkitsSchema, z.string()])).optional(),
134 + allowedTools: z.array(z.string()).optional(),
135 + manuallyManageConnections: z
136 + .boolean()
137 + .optional()
138 + .describe(
139 + `Whether to manually manage accounts. If true, you need to manage accounts manually connect user accounts.
140 +If set to false, composio will inject account maangement tools into your mcp server for agents to request and authenticate accounts.
141 +defaults to false`
142 + ),
143 +});
144 +export type MCPUpdateParams = z.infer<typeof MCPUpdateParamsSchema>;
145 +
146 +export const MCPServerConnectionStatus = z.object({
147 + connected: z.boolean(),
148 + toolkit: z.string(),
149 + connectedAccountId: z.string(),
150 +});
151 +export type MCPServerConnectionStatus = z.infer<typeof MCPServerConnectionStatus>;
152 +
153 +export const MCPServerConnectedAccountsSchema = z.record(
154 + z.string(),
155 + z.array(
156 + z.object({
157 + toolkit: z.string(),
158 + authConfigId: z.string(),
159 + connectedAccountId: z.string(),
160 + })
161 + )
162 +);
163 +export type MCPServerConnectedAccounts = z.infer<typeof MCPServerConnectedAccountsSchema>;
ts/packages/core/src/types/mcp.types.ts
+7 -3
@@ -6,7 +6,7 @@ import {
6 import { z } from 'zod';
7
8 /**
9 - * MCP Create Method Input Types
9 + * @deprecated
10 */
11 export const MCPToolkitConfigSchema = z.object({
12 toolkit: z.string().min(1, 'Toolkit name cannot be empty'),
@@ -17,7 +17,9 @@ export const MCPToolkitConfigSchema = z.object({
17 });
18
19 export type MCPToolkitConfig = z.infer<typeof MCPToolkitConfigSchema>;
20 -
20 +/**
21 + * @deprecated
22 + */
23 export const MCPToolkitConfigsArraySchema = z
24 .array(MCPToolkitConfigSchema)
25 .min(1, 'At least one toolkit configuration is required')
@@ -27,10 +29,12 @@ export const MCPToolkitConfigsArraySchema = z
29 return uniqueToolkits.size === toolkits.length;
30 }, 'Duplicate toolkits are not allowed. Each toolkit must be unique.');
31
32 +/**
33 + * @deprecated
34 + */
35 export const MCPAuthOptionsSchema = z.object({
36 isChatAuth: z.boolean().optional(),
37 });
33 -
38 export type MCPAuthOptions = z.infer<typeof MCPAuthOptionsSchema>;
39
40 export const MCPGetServerParamsSchema = z
ts/packages/core/src/types/toolRouter.types.ts new
+19
@@ -0,0 +1,19 @@
1 +import z from 'zod';
2 +
3 +export const ToolRouterToolkitConfigSchema = z.object({
4 + toolkit: z.string(),
5 + authConfigId: z.string().optional(),
6 +});
7 +
8 +export const ToolRouterConfigSchema = z.object({
9 + toolkits: z.array(z.union([z.string(), ToolRouterToolkitConfigSchema])).optional(),
10 + manuallyManageConnections: z.boolean().optional(),
11 +});
12 +
13 +export type ToolRouterConfig = z.infer<typeof ToolRouterConfigSchema>;
14 +
15 +export const ToolRouterSessionSchema = z.object({
16 + sessionId: z.string(),
17 + url: z.string(),
18 +});
19 +export type ToolRouterSession = z.infer<typeof ToolRouterSessionSchema>;
ts/packages/core/src/types/toolkit.types.ts
+3 -1
@@ -58,8 +58,10 @@ export type ToolKitListResponse = z.infer<typeof ToolKitListResponseSchema>;
58 * Toolkit retrieve response
59 */
60 export const ToolkitAuthFieldSchema = z.object({
61 - name: z.string(),
61 + description: z.string(),
62 displayName: z.string(),
63 + required: z.boolean(),
64 + name: z.string(),
65 type: z.string(),
66 default: z.string().nullable().optional(),
67 });
ts/packages/core/src/utils/session.ts
+2 -2
@@ -3,7 +3,7 @@ import { version } from '../../package.json';
3 import { ComposioRequestHeaders } from '../types/composio.types';
4
5 export function getSessionHeaders(
6 - provider: BaseComposioProvider<unknown, unknown, unknown, unknown> | undefined
6 + provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
7 ) {
8 return {
9 'x-source': provider?.name || '@composio/core',
@@ -14,7 +14,7 @@ export function getSessionHeaders(
14
15 export const getDefaultHeaders = (
16 headers: ComposioRequestHeaders | undefined,
17 - provider: BaseComposioProvider<unknown, unknown, unknown, unknown> | undefined
17 + provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
18 ) => {
19 const sessionHeaders = getSessionHeaders(provider);
20 return {
ts/packages/providers/anthropic/src/index.ts
-11
@@ -17,7 +17,6 @@ import {
17 McpUrlResponse,
18 } from '@composio/core';
19 import Anthropic from '@anthropic-ai/sdk';
20 -import { type MastraMCPServerDefinition } from '@mastra/mcp';
20 import { AnthropicTool, InputSchema } from './types';
21
22 export type AnthropicMcpServerGetResponse = {
@@ -55,7 +54,6 @@ export type AnthropicContentBlock = {
54 export class AnthropicProvider extends BaseNonAgenticProvider<
55 AnthropicToolCollection,
56 AnthropicTool,
58 - AnthropicMcpServerGetResponse,
57 AnthropicMcpServerGetResponse
58 > {
59 readonly name = 'anthropic';
@@ -132,15 +130,6 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
130 };
131 }
132
135 - /**
136 - * Note(jkomyno): right now, there's a strict dependency between the return type of this method
137 - * and the expected MCP client that will be used to retrieve the tools from it (`MCPClient` from `@mastra/mcp`).
138 - * Do we want to keep this for Anthropic?
139 - */
140 - override wrapMcpServers(servers: AnthropicMcpServerGetResponse): AnthropicMcpServerGetResponse {
141 - return servers;
142 - }
143 -
133 /**
134 * Wraps a list of Composio tools in the Anthropic format.
135 *
ts/packages/providers/cloudflare/src/index.ts
-5
@@ -25,7 +25,6 @@ type AiToolCollection = Record<string, AiTextGenerationToolInput>;
25 export class CloudflareProvider extends BaseNonAgenticProvider<
26 AiToolCollection,
27 AiTextGenerationToolInput,
28 - McpServerGetResponse,
28 McpServerGetResponse
29 > {
30 readonly name = 'cloudflare';
@@ -69,10 +68,6 @@ export class CloudflareProvider extends BaseNonAgenticProvider<
68 })) as McpServerGetResponse;
69 }
70
72 - override wrapMcpServers(data: McpServerGetResponse): McpServerGetResponse {
73 - return data;
74 - }
75 -
71 /**
72 * Wraps a Composio tool in the Cloudflare AI format.
73 *
ts/packages/providers/google/src/index.ts
+1 -19
@@ -15,7 +15,6 @@ import {
15 ExecuteToolFnOptions,
16 McpUrlResponse,
17 McpServerGetResponse,
18 - McpServerUrlInfo,
18 } from '@composio/core';
19 import { FunctionDeclaration, Schema } from '@google/genai';
20
@@ -46,8 +45,7 @@ export type GoogleGenAIToolCollection = GoogleTool[];
45 export class GoogleProvider extends BaseNonAgenticProvider<
46 GoogleGenAIToolCollection,
47 GoogleTool,
49 - McpServerGetResponse,
50 - URL
48 + McpServerGetResponse
49 > {
50 readonly name = 'google';
51
@@ -92,22 +90,6 @@ export class GoogleProvider extends BaseNonAgenticProvider<
90 })) as McpServerGetResponse;
91 }
92
95 - override wrapMcpServers(servers: McpServerGetResponse): URL {
96 - function wrapMcpServer(server: McpServerUrlInfo) {
97 - return server.url;
98 - }
99 -
100 - if (Array.isArray(servers)) {
101 - if (servers.length === 0) {
102 - throw new Error('No servers found');
103 - }
104 -
105 - return wrapMcpServer(servers[0]);
106 - }
107 -
108 - return wrapMcpServer(servers);
109 - }
110 -
93 /**
94 * Wraps a Composio tool in the Google GenAI function declaration format.
95 *
ts/packages/providers/langchain/src/index.ts
-5
@@ -23,7 +23,6 @@ export type LangChainToolCollection = Array<DynamicStructuredTool>;
23 export class LangchainProvider extends BaseAgenticProvider<
24 LangChainToolCollection,
25 DynamicStructuredTool,
26 - McpServerGetResponse,
26 McpServerGetResponse
27 > {
28 readonly name = 'langchain';
@@ -69,10 +68,6 @@ export class LangchainProvider extends BaseAgenticProvider<
68 })) as McpServerGetResponse;
69 }
70
72 - override wrapMcpServers(data: McpServerGetResponse): McpServerGetResponse {
73 - return data;
74 - }
75 -
71 /**
72 * Wraps a Composio tool in the Langchain DynamicStructuredTool format.
73 *
ts/packages/providers/mastra/src/index.ts
+1 -9
@@ -15,7 +15,6 @@ import {
15 removeNonRequiredProperties,
16 } from '@composio/core';
17 import { createTool } from '@mastra/core';
18 -import { type MastraMCPServerDefinition } from '@mastra/mcp';
18
19 export type MastraTool = ReturnType<typeof createTool>;
20
@@ -30,8 +29,7 @@ export interface MastraUrlMap {
29 export class MastraProvider extends BaseAgenticProvider<
30 MastraToolCollection,
31 MastraTool,
33 - MastraUrlMap,
34 - Record<string, MastraMCPServerDefinition>
32 + MastraUrlMap
33 > {
34 readonly name = 'mastra';
35 private strict: boolean | null;
@@ -78,12 +76,6 @@ export class MastraProvider extends BaseAgenticProvider<
76 }, {});
77 }
78
81 - override wrapMcpServers(urls: MastraUrlMap) {
82 - return Object.fromEntries(
83 - Object.entries(urls).map(([key, value]) => [key, { url: new URL(value.url) }])
84 - ) satisfies Record<string, MastraMCPServerDefinition>;
85 - }
86 -
79 wrapTool(tool: Tool, executeTool: ExecuteToolFn): MastraTool {
80 const inputParams = tool.inputParameters;
81
ts/packages/providers/openai-agents/src/index.ts
+3 -32
@@ -16,18 +16,15 @@ import {
16 ExecuteToolFn,
17 McpUrlResponse,
18 McpServerGetResponse,
19 - McpServerUrlInfo,
19 } from '@composio/core';
21 -import type { HostedMCPTool, Tool as OpenAIAgentTool } from '@openai/agents';
22 -import { tool as createOpenAIAgentTool, hostedMcpTool } from '@openai/agents';
20 +import type { Tool as OpenAIAgentTool } from '@openai/agents';
21 +import { tool as createOpenAIAgentTool } from '@openai/agents';
22
23 type OpenAIAgentsToolCollection = Array<OpenAIAgentTool>;
25 -type TMcpExperimentalResponse = Array<HostedMCPTool<unknown>>;
24 export class OpenAIAgentsProvider extends BaseAgenticProvider<
25 OpenAIAgentsToolCollection,
26 OpenAIAgentTool,
29 - McpServerGetResponse,
30 - TMcpExperimentalResponse
27 + McpServerGetResponse
28 > {
29 readonly name = 'openai-agents';
30 private strict: boolean | null;
@@ -74,32 +71,6 @@ export class OpenAIAgentsProvider extends BaseAgenticProvider<
71 })) as McpServerGetResponse;
72 }
73
77 - override wrapMcpServers(servers: McpServerGetResponse): TMcpExperimentalResponse {
78 - const prefixes = Object.keys(servers);
79 -
80 - function removePrefix(str: string): string {
81 - for (const prefix of prefixes) {
82 - if (str.startsWith(prefix)) {
83 - return str.slice(prefix.length + 1);
84 - }
85 - }
86 - return str;
87 - }
88 -
89 - function wrapMcpServer({ name, url }: McpServerUrlInfo) {
90 - return hostedMcpTool({
91 - serverLabel: removePrefix(name),
92 - serverUrl: url.toString(),
93 - });
94 - }
95 -
96 - if (Array.isArray(servers)) {
97 - return servers.map(server => wrapMcpServer(server));
98 - }
99 -
100 - return [wrapMcpServer(servers)];
101 - }
102 -
74 /**
75 * Wraps a Composio tool in a OpenAI Agents tool format.
76 *
ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+1 -11
@@ -34,15 +34,9 @@ export type OpenAIResponsesProviderOptions = {
34 /**
35 * OpenAI-specific MCP server response format
36 */
37 -export interface OpenAIMcpServerResponse {
38 - type: 'mcp';
39 - server_label: string;
40 - server_url: string;
41 -}
37 export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
38 OpenAiToolCollection,
39 OpenAiTool,
45 - OpenAiMcpTool[],
40 OpenAiMcpTool[]
41 > {
42 readonly name = 'openai';
@@ -86,7 +80,7 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
80 * @param serverName - Name of the MCP server
81 * @returns OpenAI-specific MCP server response format
82 */
89 - wrapMcpServerResponse(data: McpUrlResponse): OpenAiMcpTool[] {
83 + override wrapMcpServerResponse(data: McpUrlResponse): OpenAiMcpTool[] {
84 console.log('Wrapping MCP server response', data);
85 return data.map(item => ({
86 type: 'mcp',
@@ -96,10 +90,6 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
90 }));
91 }
92
99 - override wrapMcpServers(servers: OpenAiMcpTool[]): OpenAiMcpTool[] {
100 - return servers;
101 - }
102 -
93 /**
94 * Wraps a Composio tool in the OpenAI function calling format.
95 *
ts/packages/providers/vercel/src/index.ts
+1 -19
@@ -18,7 +18,6 @@ import {
18 McpServerGetResponse,
19 removeNonRequiredProperties,
20 jsonSchemaToZodSchema,
21 - McpServerUrlInfo,
21 } from '@composio/core';
22 import type { Tool as VercelTool } from 'ai';
23 import { tool } from 'ai';
@@ -27,8 +26,7 @@ export type VercelToolCollection = Record<string, VercelTool>;
26 export class VercelProvider extends BaseAgenticProvider<
27 VercelToolCollection,
28 VercelTool,
30 - McpServerGetResponse,
31 - URL
29 + McpServerGetResponse
30 > {
31 readonly name = 'vercel';
32 private strict: boolean | null;
@@ -58,22 +56,6 @@ export class VercelProvider extends BaseAgenticProvider<
56 this.strict = strict;
57 }
58
61 - override wrapMcpServers(servers: McpServerGetResponse): URL {
62 - function wrapMcpServer(server: McpServerUrlInfo) {
63 - return server.url;
64 - }
65 -
66 - if (Array.isArray(servers)) {
67 - if (servers.length === 0) {
68 - throw new Error('No servers found');
69 - }
70 -
71 - return wrapMcpServer(servers[0]);
72 - }
73 -
74 - return wrapMcpServer(servers);
75 - }
76 -
59 /**
60 * Wraps a Composio tool in a Vercel AI SDK tool format.
61 *