Skip to content

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

Feat: Experimental MCP and ToolRouter (#1985)

Musthaq Ahamad9a1b0e99a78c
diff --git a/.changeset/huge-shoes-see.md b/.changeset/huge-shoes-see.md
deleted file mode 100644
index 72b611a46..000000000
--- a/.changeset/huge-shoes-see.md
+++ /dev/null
@@ -1,14 +0,0 @@
----
-'@composio/core': patch
-'@composio/json-schema-to-zod': patch
-'@composio/anthropic': patch
-'@composio/cloudflare': patch
-'@composio/google': patch
-'@composio/langchain': patch
-'@composio/mastra': patch
-'@composio/openai': patch
-'@composio/openai-agents': patch
-'@composio/vercel': patch
----
-
-Add support for experimental MCP
diff --git a/.changeset/pre.json b/.changeset/pre.json
deleted file mode 100644
index aa2b819c4..000000000
--- a/.changeset/pre.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "mode": "pre",
- "tag": "rc",
- "initialVersions": {
- "composio-docs": "0.0.0",
- "@composio/core": "0.1.52",
- "@composio/json-schema-to-zod": "0.1.15",
- "@composio/anthropic": "0.1.52",
- "@composio/cloudflare": "0.1.52",
- "@composio/google": "0.1.52",
- "@composio/langchain": "0.1.52",
- "@composio/mastra": "0.1.53",
- "@composio/openai": "0.1.52",
- "@composio/openai-agents": "0.1.53",
- "@composio/vercel": "0.2.8"
- },
- "changesets": []
-}
diff --git a/.changeset/tricky-jars-wave.md b/.changeset/tricky-jars-wave.md
new file mode 100644
index 000000000..8b98b3e58
--- /dev/null
+++ b/.changeset/tricky-jars-wave.md
@@ -0,0 +1,15 @@
+---
+'@composio/core': patch
+'@composio/anthropic': patch
+'@composio/cloudflare': patch
+'@composio/google': patch
+'@composio/langchain': patch
+'@composio/mastra': patch
+'@composio/openai': patch
+'@composio/openai-agents': patch
+'@composio/vercel': patch
+---
+
+- Adds the new experiemntal ToolRouter, Deprecates the existing MCP experience and adds the new MCP components.
+- The old MCP components can be accessed via `deprecated.mcp` until the next release, where it will get removed.
+- Fixes `toolkits.list` and `toolkits.get` methods to add `description` to connection fields
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2c6feff48..a3416dbf2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -13,10 +13,10 @@ catalogs:
specifier: ^4.20250917.0
version: 4.20250917.0
'@composio/client':
- specifier: 0.1.0-alpha.36
- version: 0.1.0-alpha.36
+ specifier: 0.1.0-alpha.37
+ version: 0.1.0-alpha.37
ai:
- specifier: ^5.0.44
+ specifier: 5.0.44
version: 5.0.44
tsup:
specifier: ^8.5.0
@@ -158,7 +158,7 @@ importers:
version: 5.0.44([email protected])
composio-core:
specifier: ^0.5.39
hono:
specifier: ^4.7.11
version: 4.8.0
@@ -375,7 +375,7 @@ importers:
version: 16.5.0
zod-to-json-schema:
specifier: ^3.24.5
- version: 3.24.5([email protected])
+ version: 3.24.5([email protected])
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -446,11 +446,39 @@ importers:
specifier: 'catalog:'
version: 5.9.2
+ ts/examples/mcp:
+ dependencies:
+ '@ai-sdk/openai':
+ specifier: ^2.0.35
+ version: 2.0.35([email protected])
+ '@composio/core':
+ specifier: workspace:*
+ version: link:../../packages/core
+ '@composio/vercel':
+ specifier: workspace:*
+ version: link:../../packages/providers/vercel
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.18.0
+ version: 1.18.0
+ ai:
+ specifier: 'catalog:'
+ version: 5.0.44([email protected])
+ dotenv:
+ specifier: ^16.4.1
+ version: 16.6.1
+ devDependencies:
+ '@types/bun':
+ specifier: ^1.2.9
+ version: 1.2.16
+ typescript:
+ specifier: 'catalog:'
+ version: 5.9.2
+
ts/examples/modifiers:
dependencies:
'@ai-sdk/openai':
specifier: ^1.3.16
- version: 1.3.22([email protected])
+ version: 1.3.22([email protected])
'@composio/core':
specifier: workspace:*
version: link:../../packages/core
@@ -459,7 +487,7 @@ importers:
version: link:../../packages/providers/vercel
ai:
specifier: 'catalog:'
- version: 5.0.44([email protected])
+ version: 5.0.44([email protected])
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -483,8 +511,8 @@ importers:
specifier: ^1.18.0
version: 1.18.0
'@openai/agents':
- specifier: ^0.1.3
+ specifier: ^0.1.4
dotenv:
specifier: ^16.4.1
version: 16.5.0
@@ -525,7 +553,7 @@ importers:
dependencies:
'@ai-sdk/openai':
specifier: ^1.3.16
- version: 1.3.22([email protected])
+ version: 1.3.22([email protected])
'@composio/core':
specifier: workspace:*
version: link:../../packages/core
@@ -534,7 +562,7 @@ importers:
version: link:../../packages/providers/vercel
ai:
specifier: 'catalog:'
- version: 5.0.44([email protected])
+ version: 5.0.44([email protected])
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -553,10 +581,10 @@ importers:
version: 16.5.0
openai:
specifier: ^5.19.1
zod-to-json-schema:
specifier: ^3.24.5
- version: 3.24.5([email protected])
+ version: 3.24.5([email protected])
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -585,7 +613,7 @@ importers:
dependencies:
'@ai-sdk/openai':
specifier: ^2.0.16
- version: 2.0.16([email protected])
+ version: 2.0.16([email protected])
'@composio/core':
specifier: workspace:*
version: link:../../packages/core
@@ -597,7 +625,7 @@ importers:
version: 1.18.0
ai:
specifier: 'catalog:'
- version: 5.0.44([email protected])
+ version: 5.0.44([email protected])
dotenv:
specifier: ^16.5.0
version: 16.5.0
@@ -632,7 +660,7 @@ importers:
version: 1.0.0-alpha.1
'@composio/client':
specifier: 'catalog:'
- version: 0.1.0-alpha.36
+ version: 0.1.0-alpha.37
'@composio/core':
specifier: workspace:*
version: link:../core
@@ -726,7 +754,7 @@ importers:
dependencies:
'@composio/client':
specifier: 'catalog:'
- version: 0.1.0-alpha.36
+ version: 0.1.0-alpha.37
'@composio/json-schema-to-zod':
specifier: workspace:*
version: link:../json-schema-to-zod
@@ -802,7 +830,7 @@ importers:
version: 0.52.0
'@mastra/mcp':
specifier: ^0.12.0
devDependencies:
'@composio/core':
specifier: workspace:*
@@ -1015,6 +1043,12 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-LelCyotLQtL6lRYAvmtNvLyWirCR4YXr2aE4gXUXtpE+Y43eU1xdI3Jyq3Ugsvv2VhyKEceZRkrSFBmozrt21w==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4
+
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}
engines: {node: '>=18'}
@@ -1216,8 +1250,8 @@ packages:
'@cloudflare/[email protected]':
resolution: {integrity: sha512-Lsn9dZoRYZZCXXHZNa50cMP8kWhQZG9M7WjxNSiXFzC8bk4Wh/0SYYo4YINxEjEt6h2o69LmAhFaJ+qgaJTh8Q==}
- '@composio/[email protected]':
- resolution: {integrity: sha512-YRsx5rRWFoT2kyzYTsJ5lDd6dZI2KmkLxdnaQdACc7A/DkFHzhZraSROaYLElYUP+2ScK4WynVU6+IaHzYn2KA==}
+ '@composio/[email protected]':
+ resolution: {integrity: sha512-2YzXiRXlxqOgEz7nEh1aKdJ9vwQRb69+RX6UH+LTDmuTwW+pOjI2qbhIBxTbP2z9e2SyHVG0/AtMxc9tR5jU0w==}
'@composio/[email protected]':
resolution: {integrity: sha512-LrTOGR0vPo7/YWENGBfdB9cOt0C7uFxwISwv0gwu+8tSVsa7MgoZqREBpFA29E1Fb7ss1tlpAZusy4ojPeXKnQ==}
@@ -1800,138 +1834,163 @@ packages:
resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-IVfGJa7gjChDET1dK9SekxFFdflarnUB8PwW8aGwEoF3oAsSDuNUTYS+SKDOyOJxQyDC1aPFMuRYLoDInyV9Ew==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-s8BAd0lwUIvYCJyRdFqvsj+BJIpDBSxs6ivrOPm/R7piTs5UIwY5OjXrP2bqXC9/moGsyRa37eYWYCOGVXxVrA==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-tiXxFZFbhnkWE2LA8oQj7KYR+bWBkiV2nilRldT7bqoEZ4HiDOcePr9wVDAZPi/Id5fT1oY9iGnDq20cwUz8lQ==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-xukSwvhguw7COyzvmjydRb3x/09+21HykyapcZchiCUkTThEQEOMtBj9UhkaBRLuBrgLFzQ2wbxdeCCJW/jgJA==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-yRj2+reB8iMg9W5sULM3S74jVS7zqSzHG3Ol/twnAAkAhnGQnpjj6e4ayUz7V+FpKypwgs82xbRdYtchTTUB+Q==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-jYZdG+whg0MDK+q2COKbYidaqW/WTz0cc1E+tMAusiDygrM4ypmSCjOJPmFTvHHJ8j/6cAGyeDWZOsK06tP33w==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-wK7SBdwrAiycjXdkPnGCPLjYb9lD4l6Ze2gSdAGVZrEL05AOUJESWU2lhlC+Ffn5/G+VKuSm6zzbQSzFX/P65A==}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-D8n8wgWmPDakc83LORcfJepdOSN6MvWNzzz2ux0MnIbOqdieRZwVYY32zxVx+IFUT8er5KPcyU3XXsn+GzG/0Q==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-0DZzkvuEOqQUP9mo2kjjKNok5AmnOr1jB2XYjkaoNRwpAYMDzRmAqUIa1nRi58S2WswqSfPOWLNOr0FDT3H5RQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-EGZ1xwhBI7dNISwxjChqBGELCWMGDvmxZXKjQRuqMrakhO8QoMgqCrdjnAqJq/CScxfRn+Bb7suXBElKQpPDiw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-sD7J+h5nFLMMmOXYH4DD9UtSNBD05tWSSdWAcEyzqW8Cn5UxXvsHAxmxSesYUsTOBmUnjtxghKDl15EvfqLFbQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-NEE2vQ6wcxYav1/A22OOxoSOGiKnNmDzCYFOZ949xFmrWZOVII1Bp3NqVVpvj+3UeHMFyN5eP/V5hzViQ5CZNA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-DOYMrDm5E6/8bm/yQLCWyuDJwUnlevR8xtF8bs+gjZ7cyUNYXiSf/E8Kp0Ss5xasIaXSHzb888V1BE4i1hFhAA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==}
@@ -2229,24 +2288,28 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-wFyZ7X470YJQtpKot4xCY3gpdn8lE9nTlldG07/kJYexCUpX1piX+MBfZdvulo+t1yADFVEuzFfVHfklfEx8kw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-gEbH9rv9o7I12qPyvZNVTyP/PWKqOp8clvnoYZQiX800KkqsaJZuOXkWgMa7ANCCh/oEN2ZQheh3yH8/kWPSEg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-Cf8sr0ufuC/nu/yQ76AnarbSAXcwG/wj+1xFPNbyNo8ltA6kw5d5YqO8kQuwVIxk13SBdtgXrNyom3ZosHAy4A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-ay5+qADDN3rwRbRpEhTOreOn1OyJIXS60tg9WMYTWCy3fB6rGoyjLVxc4dR9PYjEdR2iDYsaF5h03NA+XuYPQQ==}
@@ -2280,21 +2343,44 @@ packages:
zod:
optional: true
+ '@openai/[email protected]':
+ resolution: {integrity: sha512-7GWq5qRaYVJ+NXx92MXLOpkUthVsW2SIsQZHH0U2uKZJlvwbYWKY/lJGSJ3Kg9CkATEhn+p5U0CugNk6k/eXXw==}
+ peerDependencies:
+ zod: ^3.25.40
+ peerDependenciesMeta:
+ zod:
+ optional: true
+
'@openai/[email protected]':
resolution: {integrity: sha512-nyC+ShxxLtDtQrcAdpfegmrmOKou0jHPrl1iTFizo2f/KqeJ0n8OvNOmiixMxYgAOA2D3KqxdkHcgdAIQlH7TQ==}
peerDependencies:
zod: ^3.25.40
+ '@openai/[email protected]':
+ resolution: {integrity: sha512-kHAjnXvpP4CLcHeswuhluRLgg6DnozW7wQgc8SUg9M1vzHfez+61ZhkijffhHTgzmGICLVFHrBrtDTvRqoSAcw==}
+ peerDependencies:
+ zod: ^3.25.40
+
'@openai/[email protected]':
resolution: {integrity: sha512-8uB63JuZkGew+Ccd+aZg2C4FkCRu3MpVg/+6veJzrYzjYsJx8ncUUTIYzDBs71m86+WJwlzmKv0pcGAzbMXx5g==}
peerDependencies:
zod: ^3.25.40
+ '@openai/[email protected]':
+ resolution: {integrity: sha512-d8DwwT/lCoXjWPr0/yT2/RQ35zqJa5aOf66YI6LJmBlHZp9RV7v/Jq81vuPQBK+CRK2LLe8UzBZHkZHTYY4m+Q==}
+ peerDependencies:
+ zod: ^3.25.40
+
'@openai/[email protected]':
resolution: {integrity: sha512-uGB831WPmUuJjCVIKbAcFMZLokkfSu/F7XSlbMs1mfCP1yD+47ZGQbn0C0PPiOoMN05dbmaq9tbYbjVYbruhDA==}
peerDependencies:
zod: ^3.25.40
+ '@openai/[email protected]':
+ resolution: {integrity: sha512-Zfo1I9SEKkbyBBjn8IsdXnYT+AOm7M1FuaS+oA6X+KouX4WjSR0oRTV5dmpv1F6VVyDg4hz6Ux1GvIi84gspEQ==}
+ peerDependencies:
+ zod: ^3.25.40
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==}
engines: {node: '>=8.0.0'}
@@ -2787,36 +2873,42 @@ packages:
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==}
engines: {node: '>= 10.0.0'}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==}
engines: {node: '>= 10.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@parcel/[email protected]':
resolution: {integrity: sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==}
engines: {node: '>= 10.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@parcel/[email protected]':
resolution: {integrity: sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==}
@@ -2930,56 +3022,67 @@ packages:
resolution: {integrity: sha512-gTJ/JnnjCMc15uwB10TTATBEhK9meBIY+gXP4s0sHD1zHOaIh4Dmy1X9wup18IiY9tTNk5gJc4yx9ctj/fjrIw==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-ZJ3gZynL1LDSIvRfz0qXtTNs56n5DI2Mq+WACWZ7yGHFUEirHBRt7fyIk0NsCKhmRhn7WAcjgSkSVVxKlPNFFw==}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-8FnkipasmOOSSlfucGYEu58U8cxEdhziKjPD2FIa0ONVMxvl/hmONtX/7y4vGjdUhjcTHlKlDhw3H9t98fPvyA==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-KPPyAdlcIZ6S9C3S2cndXDkV0Bb1OSMsX0Eelr2Bay4EsF9yi9u9uzc9RniK3mcUGCLhWY9oLr6er80P5DE6XA==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-HPGDIH0/ZzAZjvtlXj6g+KDQ9ZMHfSP553za7o2Odegb/BEfwJcR0Sw0RLNpQ9nC6Gy8s+3mSS9xjZ0n3rhcYg==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-gEmwbOws4U4GLAJDhhtSPWPXUzDfMRedT3hFMyRAvM9Mrnj+dJIFIeL7otsv2WF3D7GrV0GIewW0y28dOYWkmw==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-XXKvo2e+wFtXZF/9xoWohHg+MuRnvO29TI5Hqe9xwN5uN8NKUYy7tXUG3EZAlfchufNCTHNGjEx7uN78KsBo0g==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-ruf3hPWhjw6uDFsOAzmbNIvlXFXlBQ4nk57Sec8E8rUxs/AI4HD6xmiiasOOx/3QxS2f5eQMKTAwk7KHwpzr/Q==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-QmNIAqDiEMEvFV15rsSnjoSmO0+eJLoKRD9EAa9rrYNwO/XRCtOGM3A5A0X+wmG+XRrw9Fxdsw+LnyYiZWWcVw==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-jAHr/S0iiBtFyzjhOkAics/2SrXE092qyqEg96e90L3t9Op8OTzS6+IX0Fy5wCt2+KqeHAkti+eitV0wvblEoQ==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-3yATWgdeXyuHtBhrLt98w+5fKurdqvs8B53LaoKD7P7H7FKOONLsBVMNl9ghPQZQuYcceV5CDyPfyfGpMWD9mQ==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-wVzXp2qDSCOpcBCT5WRWLmpJRIzv23valvcTwMHEobkjippNf+C3ys/+wf07poPkeNix0paTNemB2XrHr2TnGw==}
@@ -6489,47 +6592,29 @@ snapshots:
'@ai-sdk/provider-utils': 3.0.7([email protected])
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider': 2.0.0
- '@ai-sdk/provider-utils': 3.0.7([email protected])
- zod: 4.1.9
-
dependencies:
'@ai-sdk/provider': 2.0.0
'@ai-sdk/provider-utils': 3.0.9([email protected])
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider': 2.0.0
- '@ai-sdk/provider-utils': 3.0.9([email protected])
- zod: 4.1.9
-
dependencies:
'@ai-sdk/provider': 1.1.3
'@ai-sdk/provider-utils': 2.2.8([email protected])
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- zod: 4.1.9
-
dependencies:
'@ai-sdk/provider': 2.0.0
'@ai-sdk/provider-utils': 3.0.4([email protected])
zod: 3.25.76
dependencies:
'@ai-sdk/provider': 2.0.0
- '@ai-sdk/provider-utils': 3.0.4([email protected])
- zod: 4.1.9
+ '@ai-sdk/provider-utils': 3.0.9([email protected])
+ zod: 3.25.76
dependencies:
@@ -6538,13 +6623,6 @@ snapshots:
secure-json-parse: 2.7.0
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider': 1.1.3
- nanoid: 3.3.11
- secure-json-parse: 2.7.0
- zod: 4.1.9
-
dependencies:
'@ai-sdk/provider': 2.0.0
@@ -6553,14 +6631,6 @@ snapshots:
zod: 3.25.76
zod-to-json-schema: 3.24.6([email protected])
- dependencies:
- '@ai-sdk/provider': 2.0.0
- '@standard-schema/spec': 1.0.0
- eventsource-parser: 3.0.3
- zod: 4.1.9
- zod-to-json-schema: 3.24.6([email protected])
-
dependencies:
'@ai-sdk/provider': 2.0.0
@@ -6569,14 +6639,6 @@ snapshots:
zod: 3.25.76
zod-to-json-schema: 3.24.6([email protected])
- dependencies:
- '@ai-sdk/provider': 2.0.0
- '@standard-schema/spec': 1.0.0
- eventsource-parser: 3.0.6
- zod: 4.1.9
- zod-to-json-schema: 3.24.6([email protected])
-
dependencies:
'@ai-sdk/provider': 2.0.0
@@ -6584,13 +6646,6 @@ snapshots:
eventsource-parser: 3.0.6
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider': 2.0.0
- '@standard-schema/spec': 1.0.0
- eventsource-parser: 3.0.6
- zod: 4.1.9
-
dependencies:
'@ai-sdk/provider': 2.0.0
@@ -6598,13 +6653,6 @@ snapshots:
eventsource-parser: 3.0.6
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider': 2.0.0
- '@standard-schema/spec': 1.0.0
- eventsource-parser: 3.0.6
- zod: 4.1.9
-
'@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
@@ -6623,16 +6671,6 @@ snapshots:
optionalDependencies:
zod: 3.25.76
- dependencies:
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- '@ai-sdk/ui-utils': 1.2.11([email protected])
- react: 18.3.1
- swr: 2.3.3([email protected])
- throttleit: 2.1.0
- optionalDependencies:
- zod: 4.1.9
-
dependencies:
'@ai-sdk/provider': 1.1.3
@@ -6640,13 +6678,6 @@ snapshots:
zod: 3.25.76
zod-to-json-schema: 3.24.6([email protected])
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- zod: 4.1.9
- zod-to-json-schema: 3.24.6([email protected])
-
'@alloc/[email protected]': {}
'@anthropic-ai/[email protected]': {}
@@ -6871,7 +6902,7 @@ snapshots:
'@cloudflare/[email protected]': {}
- '@composio/[email protected]': {}
+ '@composio/[email protected]': {}
'@composio/[email protected](@composio/core@ts+packages+core)(@google/[email protected](@modelcontextprotocol/[email protected]))':
dependencies:
@@ -7761,63 +7792,6 @@ snapshots:
- valibot
- zod-openapi
- dependencies:
- '@a2a-js/sdk': 0.2.5
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- '@ai-sdk/provider-utils-v5': '@ai-sdk/[email protected]([email protected])'
- '@ai-sdk/provider-v5': '@ai-sdk/[email protected]'
- '@ai-sdk/ui-utils': 1.2.11([email protected])
- '@opentelemetry/api': 1.9.0
- '@opentelemetry/auto-instrumentations-node': 0.62.1(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))
- '@opentelemetry/core': 2.0.1(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-grpc': 0.203.0(@opentelemetry/[email protected])
- '@opentelemetry/exporter-trace-otlp-http': 0.203.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-exporter-base': 0.203.0(@opentelemetry/[email protected])
- '@opentelemetry/otlp-transformer': 0.203.0(@opentelemetry/[email protected])
- '@opentelemetry/resources': 2.0.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-metrics': 2.0.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-node': 0.203.0(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-base': 2.0.1(@opentelemetry/[email protected])
- '@opentelemetry/sdk-trace-node': 2.0.1(@opentelemetry/[email protected])
- '@opentelemetry/semantic-conventions': 1.36.0
- '@sindresorhus/slugify': 2.2.1
- date-fns: 3.6.0
- dotenv: 16.6.1
- hono: 4.9.7
- js-tiktoken: 1.0.20
- json-schema: 0.4.0
- json-schema-to-zod: 2.6.1
- p-map: 7.0.3
- pino: 9.7.0
- pino-pretty: 13.0.0
- radash: 12.1.1
- sift: 17.1.3
- xstate: 5.20.2
- zod: 4.1.9
- zod-to-json-schema: 3.24.6([email protected])
- transitivePeerDependencies:
- - '@hono/arktype-validator'
- - '@hono/effect-validator'
- - '@hono/typebox-validator'
- - '@hono/valibot-validator'
- - '@hono/zod-validator'
- - '@sinclair/typebox'
- - '@valibot/to-json-schema'
- - arktype
- - effect
- - encoding
- - openapi-types
- - react
- - supports-color
- - valibot
- - zod-openapi
-
dependencies:
'@apidevtools/json-schema-ref-parser': 14.2.1(@types/[email protected])
@@ -7834,22 +7808,6 @@ snapshots:
- '@types/json-schema'
- supports-color
- dependencies:
- '@apidevtools/json-schema-ref-parser': 14.2.1(@types/[email protected])
- '@modelcontextprotocol/sdk': 1.18.0
- date-fns: 4.1.0
- exit-hook: 4.0.0
- fast-deep-equal: 3.1.3
- uuid: 11.1.0
- zod: 4.1.9
- zod-from-json-schema: 0.5.0
- zod-from-json-schema-v3: [email protected]
- transitivePeerDependencies:
- - '@types/json-schema'
- - supports-color
-
dependencies:
@@ -7859,15 +7817,6 @@ snapshots:
zod-from-json-schema-v3: [email protected]
zod-to-json-schema: 3.24.6([email protected])
- dependencies:
- json-schema: 0.4.0
- zod: 4.1.9
- zod-from-json-schema: 0.5.0
- zod-from-json-schema-v3: [email protected]
- zod-to-json-schema: 3.24.6([email protected])
-
'@modelcontextprotocol/[email protected]':
dependencies:
ajv: 6.12.6
@@ -7952,6 +7901,17 @@ snapshots:
- supports-color
- ws
+ dependencies:
+ debug: 4.4.1([email protected])
+ optionalDependencies:
+ '@modelcontextprotocol/sdk': 1.18.0
+ zod: 3.25.76
+ transitivePeerDependencies:
+ - supports-color
+ - ws
+
dependencies:
'@openai/agents-core': 0.1.3([email protected])([email protected])
@@ -7962,6 +7922,16 @@ snapshots:
- supports-color
- ws
+ dependencies:
+ '@openai/agents-core': 0.1.4([email protected])([email protected])
+ debug: 4.4.1([email protected])
+ zod: 3.25.76
+ transitivePeerDependencies:
+ - supports-color
+ - ws
+
dependencies:
'@openai/agents-core': 0.1.3([email protected])([email protected])
@@ -7974,6 +7944,18 @@ snapshots:
- supports-color
- utf-8-validate
+ dependencies:
+ '@openai/agents-core': 0.1.4([email protected])([email protected])
+ '@types/ws': 8.18.1
+ debug: 4.4.1([email protected])
+ ws: 8.18.2
+ zod: 3.25.76
+ transitivePeerDependencies:
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+
dependencies:
'@openai/agents-core': 0.1.3([email protected])([email protected])
@@ -7988,6 +7970,20 @@ snapshots:
- utf-8-validate
- ws
+ dependencies:
+ '@openai/agents-core': 0.1.4([email protected])([email protected])
+ '@openai/agents-openai': 0.1.4([email protected])([email protected])
+ '@openai/agents-realtime': 0.1.4([email protected])
+ debug: 4.4.1([email protected])
+ zod: 3.25.76
+ transitivePeerDependencies:
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - ws
+
'@opentelemetry/[email protected]':
dependencies:
'@opentelemetry/api': 1.9.0
@@ -9171,14 +9167,6 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
- dependencies:
- '@vitest/spy': 3.2.4
- estree-walker: 3.0.3
- magic-string: 0.30.17
- optionalDependencies:
-
dependencies:
'@vitest/spy': 3.2.4
@@ -9187,14 +9175,6 @@ snapshots:
optionalDependencies:
- dependencies:
- '@vitest/spy': 3.2.4
- estree-walker: 3.0.3
- magic-string: 0.30.17
- optionalDependencies:
-
'@vitest/[email protected]':
dependencies:
tinyrainbow: 2.0.0
@@ -9224,7 +9204,7 @@ snapshots:
sirv: 3.0.1
tinyglobby: 0.2.14
tinyrainbow: 2.0.0
'@vitest/[email protected]':
dependencies:
@@ -9278,18 +9258,6 @@ snapshots:
optionalDependencies:
react: 18.3.1
- dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
- '@ai-sdk/react': 1.2.12([email protected])([email protected])
- '@ai-sdk/ui-utils': 1.2.11([email protected])
- '@opentelemetry/api': 1.9.0
- jsondiffpatch: 0.6.0
- zod: 4.1.9
- optionalDependencies:
- react: 18.3.1
-
dependencies:
'@ai-sdk/gateway': 1.0.15([email protected])
@@ -9298,14 +9266,6 @@ snapshots:
'@opentelemetry/api': 1.9.0
zod: 3.25.76
- dependencies:
- '@ai-sdk/gateway': 1.0.15([email protected])
- '@ai-sdk/provider': 2.0.0
- '@ai-sdk/provider-utils': 3.0.7([email protected])
- '@opentelemetry/api': 1.9.0
- zod: 4.1.9
-
dependencies:
'@ai-sdk/gateway': 1.0.23([email protected])
@@ -9314,14 +9274,6 @@ snapshots:
'@opentelemetry/api': 1.9.0
zod: 3.25.76
- dependencies:
- '@ai-sdk/gateway': 1.0.23([email protected])
- '@ai-sdk/provider': 2.0.0
- '@ai-sdk/provider-utils': 3.0.9([email protected])
- '@opentelemetry/api': 1.9.0
- zod: 4.1.9
-
dependencies:
fast-deep-equal: 3.1.3
@@ -9629,9 +9581,9 @@ snapshots:
has-own-prop: 2.0.0
repeat-string: 1.6.1
dependencies:
- '@ai-sdk/openai': 2.0.16([email protected])
+ '@ai-sdk/openai': 2.0.35([email protected])
'@cloudflare/workers-types': 4.20250917.0
'@composio/mcp': 1.0.3-0
'@hey-api/client-axios': 0.2.12([email protected])
@@ -10450,15 +10402,6 @@ snapshots:
hono: 4.9.7
zod: 3.25.76
- dependencies:
- json-schema-walker: 2.0.0
- openapi-types: 12.1.3
- optionalDependencies:
- effect: 3.16.16
- hono: 4.9.7
- zod: 4.1.9
-
@@ -11107,10 +11050,10 @@ snapshots:
ws: 8.18.2
zod: 3.25.76
optionalDependencies:
ws: 8.18.2
- zod: 4.1.9
+ zod: 3.25.76
optionalDependencies:
@@ -12342,7 +12285,7 @@ snapshots:
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
@@ -12426,7 +12369,7 @@ snapshots:
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
@@ -12621,18 +12564,10 @@ snapshots:
dependencies:
zod: 3.25.76
- dependencies:
- zod: 4.1.9
-
dependencies:
zod: 3.25.76
- dependencies:
- zod: 4.1.9
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index e25bdaaec..3d99c56ca 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,35 +1,31 @@
packages:
-- "ts/packages/core"
-- "ts/packages/cli"
-- "ts/packages/json-schema-to-zod"
-- "ts/packages/providers/*"
-- "ts/packages/ts-builders"
-- "ts/packages/wrappers/*"
-- "ts/examples/*"
-- "fern"
-- "fern/llms-txt-worker"
-- "fern/pages/examples/*"
-- "fern/snippets/*"
+ - ts/packages/core
+ - ts/packages/cli
+ - ts/packages/json-schema-to-zod
+ - ts/packages/providers/*
+ - ts/packages/ts-builders
+ - ts/packages/wrappers/*
+ - ts/examples/*
+ - fern
+ - fern/llms-txt-worker
+ - fern/pages/examples/*
+ - fern/snippets/*
-# See: https://pnpm.io/catalogs
catalog:
- "@composio/client": 0.1.0-alpha.36
- "@cloudflare/vitest-pool-workers": ^0.9.2
- "@cloudflare/workers-types": ^4.20250917.0
- "ai": ^5.0.44
- "openai": ^5.20.3
- "uuid": ^13.0.0
- "tsup": ^8.5.0
- "tsx": ^4.20.5
- "typescript": ^5.9.2
- "vitest": ^3.2.4
- "wrangler": ^4.37.0
+ '@cloudflare/vitest-pool-workers': ^0.9.2
+ '@cloudflare/workers-types': ^4.20250917.0
+ '@composio/client': 0.1.0-alpha.37
+ ai: 5.0.44
+ openai: ^5.20.3
+ tsup: ^8.5.0
+ tsx: ^4.20.5
+ typescript: ^5.9.2
+ uuid: ^13.0.0
+ vitest: ^3.2.4
+ wrangler: ^4.37.0
+ zod: 3.25.76
- # According to https://github.com/langchain-ai/langchainjs/issues/8468, v3.25.75 is broken. v3.25.76 is probably broken as well,
- # as it causes "error TS2589: Type instantiation is excessively deep and possibly infinite." in `./ts/packages/providers/langchain/src/index.ts`.
- # However, most packages imported elsewhere (e.g., ´@ai-sdk/*`) require `zod: ^3.25.76 || ^4`.
- # Hence, we have to use at least v3.25.76 for now, and "accept" and ignore the above TS2589 error in `@composio/langchain`.
- "zod": 3.25.76
+minimumReleaseAge: 1440
-# See: https://pnpm.io/settings#minimumreleaseage
-minimumReleaseAge: 1440 # 1 day
+minimumReleaseAgeExclude:
+ - '@composio/client'
diff --git a/python/composio/core/models/__init__.py b/python/composio/core/models/__init__.py
index 41916e4d6..478d7b281 100644
--- a/python/composio/core/models/__init__.py
+++ b/python/composio/core/models/__init__.py
@@ -1,5 +1,6 @@
from .auth_configs import AuthConfigs
from .connected_accounts import ConnectedAccounts
+from .mcp import MCP
from .toolkits import Toolkits
from .tools import Tools
from .triggers import Triggers
@@ -7,6 +8,7 @@ from .triggers import Triggers
__all__ = [
"AuthConfigs",
"ConnectedAccounts",
+ "MCP",
"Toolkits",
"Tools",
"Triggers",
diff --git a/python/composio/core/models/mcp.py b/python/composio/core/models/mcp.py
new file mode 100644
index 000000000..75b9b0b8e
--- /dev/null
+++ b/python/composio/core/models/mcp.py
@@ -0,0 +1,468 @@
+"""
+MCP (Model Control Protocol) module for Composio SDK.
+
+This module provides MCP server operations
+"""
+
+from __future__ import annotations
+
+import typing as t
+
+import typing_extensions as te
+
+from composio_client import omit
+from composio_client.types.mcp.custom_create_response import CustomCreateResponse
+from composio.client import HttpClient
+from composio.core.models.base import Resource
+from composio.core.types import MCPToolkitConfig
+from composio.exceptions import ValidationError
+
+
+# Data Types (matching TypeScript specification)
+
+
+class MCPServerInstance(te.TypedDict):
+ """MCP Server Instance data structure (matching TypeScript implementation)."""
+
+ id: str
+ name: str
+ type: str
+ url: str # User-specific connection URL
+ user_id: str # Associated user ID
+ allowed_tools: t.List[str] # Available tools for the user
+ auth_configs: t.List[str] # Associated auth configurations
+
+
+class MCPItem(te.TypedDict):
+ """Complete MCP server information."""
+
+ id: str # Unique server identifier
+ name: str # Human-readable server name
+ allowed_tools: t.List[str] # Array of enabled tool identifiers
+ auth_config_ids: t.List[str] # Array of auth configuration IDs
+ toolkits: t.List[str] # Array of toolkit names
+ commands: t.Dict[str, str] # Setup commands for different clients
+ mcp_url: str # Server connection URL
+ toolkit_icons: t.Dict[str, str] # Map of toolkit icons
+ server_instance_count: int # Number of active instances
+ created_at: te.NotRequired[t.Optional[str]]
+ updated_at: te.NotRequired[t.Optional[str]]
+
+
+class MCPListResponse(te.TypedDict):
+ """Paginated list response."""
+
+ items: t.List[t.Any] # Array of MCP server objects (raw API response)
+ current_page: int # Current page number
+ total_pages: int # Total number of pages
+
+
+def _add_generate_method(
+ response: CustomCreateResponse, mcp_instance: "MCP"
+) -> CustomCreateResponse:
+ """Add generate method to CustomCreateResponse object."""
+
+ def generate(
+ user_id: str, manually_manage_connections: t.Optional[bool] = None
+ ) -> MCPServerInstance:
+ """
+ Generate server instance for this MCP configuration.
+ Matches TypeScript server.generate(userId) method.
+
+ :param user_id: External user ID from your database
+ :param manually_manage_connections: Whether to manually manage connections (optional)
+ :return: MCP server instance
+ """
+ return mcp_instance.generate(user_id, response.id, manually_manage_connections)
+
+ # Add the generate method to the response object
+ response.generate = generate
+ return response
+
+
+class MCP(Resource):
+ """
+ MCP (Model Control Protocol) class.
+ Provides enhanced MCP server operations
+
+ This matches the TypeScript ExperimentalMCP class functionality.
+ """
+
+ def __init__(self, client: HttpClient):
+ """
+ Initialize MCP instance.
+
+ :param client: HTTP client for API calls
+ """
+ super().__init__(client)
+
+ def create(
+ self,
+ name: str,
+ toolkits: t.List[t.Union[MCPToolkitConfig, str]],
+ manually_manage_connections: bool = False,
+ allowed_tools: t.Optional[t.List[str]] = None,
+ ) -> CustomCreateResponse:
+ """
+ Create a new MCP server configuration with specified toolkits and authentication settings.
+
+ :param name: Unique name for the MCP configuration
+ :param toolkits: List of toolkit configurations. Can be either:
+ - MCPToolkitConfig objects with detailed configuration
+ - Strings representing toolkit names (for simple cases)
+ :param manually_manage_connections: Whether to manually manage account connections (default: False)
+ :param allowed_tools: List of specific tools to enable across all toolkits (default: None for all tools)
+ :return: Created server details with generate method
+
+ Examples:
+ >>> # Using toolkit configuration objects with auth
+ >>> server = composio.experimental.mcp.create(
+ ... 'personal-mcp-server',
+ ... toolkits=[
+ ... {
+ ... 'toolkit': 'github',
+ ... 'auth_config_id': 'ac_xyz',
+ ... },
+ ... {
+ ... 'toolkit': 'slack',
+ ... 'auth_config_id': 'ac_abc',
+ ... },
+ ... ],
+ ... allowed_tools=['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS', 'SLACK_SEND_MESSAGE'],
+ ... manually_manage_connections=False
+ ... )
+ >>>
+ >>> # Using simple toolkit names (most common usage)
+ >>> server = composio.experimental.mcp.create(
+ ... 'simple-mcp-server',
+ ... toolkits=['composio_search', 'text_to_pdf'],
+ ... allowed_tools=['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH', 'TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
+ ... )
+ >>>
+ >>> # Using all tools from toolkits (default behavior)
+ >>> server = composio.experimental.mcp.create(
+ ... 'all-tools-server',
+ ... toolkits=['composio_search', 'text_to_pdf']
+ ... # allowed_tools=None means all tools from these toolkits
+ ... )
+ >>>
+ >>> # Get server instance for a user
+ >>> mcp = server.generate('user_12345')
+ """
+ if not toolkits:
+ raise ValidationError("At least one toolkit configuration is required")
+
+ try:
+ # Normalize toolkits to MCPToolkitConfig format
+ normalized_toolkit_configs = []
+ for toolkit in toolkits:
+ if isinstance(toolkit, str):
+ # Convert string to MCPToolkitConfig
+ normalized_toolkit_configs.append({"toolkit": toolkit})
+ else:
+ # Already MCPToolkitConfig, use as-is
+ normalized_toolkit_configs.append(toolkit)
+
+ # Extract toolkits and prepare for API call
+ toolkit_configs = normalized_toolkit_configs
+
+ # Get unique toolkits and auth config IDs
+ toolkit_names = []
+ auth_config_ids = []
+
+ for toolkit_config in toolkit_configs:
+ if (
+ "toolkit" in toolkit_config
+ and toolkit_config["toolkit"] not in toolkit_names
+ ):
+ toolkit_names.append(toolkit_config["toolkit"])
+
+ if (
+ "auth_config_id" in toolkit_config
+ and toolkit_config["auth_config_id"] not in auth_config_ids
+ ):
+ auth_config_ids.append(toolkit_config["auth_config_id"])
+
+ # Use the allowed_tools parameter instead of individual toolkit configs
+ custom_tools = allowed_tools if allowed_tools is not None else omit
+
+ # Use the custom MCP create endpoint
+ response = self._client.mcp.custom.create(
+ name=name,
+ toolkits=toolkit_names,
+ auth_config_ids=auth_config_ids,
+ custom_tools=custom_tools,
+ managed_auth_via_composio=not manually_manage_connections,
+ )
+
+ # Return response with generate method (matching TypeScript behavior)
+ return _add_generate_method(response, self)
+
+ except Exception as e:
+ raise ValidationError("Failed to create MCP server") from e
+
+ def list(
+ self,
+ page_no: t.Optional[int] = None,
+ limit: t.Optional[int] = None,
+ toolkits: t.Optional[str] = None,
+ auth_config_ids: t.Optional[str] = None,
+ name: t.Optional[str] = None,
+ order_by: t.Optional[str] = None,
+ order_direction: t.Optional[str] = None,
+ ) -> MCPListResponse:
+ """
+ List MCP servers with optional filtering and pagination.
+
+ :param page_no: Page number for pagination (default: 1)
+ :param limit: Maximum items per page (default: 10)
+ :param toolkits: Filter by toolkit name (single string)
+ :param auth_config_ids: Filter by auth configuration ID (single string)
+ :param name: Filter by server name (partial match)
+ :param order_by: Order by field ('created_at' or 'updated_at')
+ :param order_direction: Order direction ('asc' or 'desc')
+ :return: Paginated list of MCP servers
+
+ Examples:
+ >>> # List all servers
+ >>> all_servers = composio.experimental.mcp.list()
+ >>>
+ >>> # List with pagination
+ >>> paged_servers = composio.experimental.mcp.list(page_no=2, limit=5)
+ >>>
+ >>> # Filter by toolkit
+ >>> github_servers = composio.experimental.mcp.list(toolkits='github', name='personal')
+ """
+
+ try:
+ # Use the MCP list endpoint with filters
+ response = self._client.mcp.list(
+ page_no=page_no,
+ limit=limit,
+ toolkits=toolkits,
+ auth_config_ids=auth_config_ids,
+ name=name,
+ order_by=order_by,
+ order_direction=order_direction,
+ )
+
+ items = (
+ response.items if hasattr(response, "items") and response.items else []
+ )
+
+ return MCPListResponse(
+ items=items,
+ current_page=getattr(response, "current_page", page_no or 1),
+ total_pages=getattr(response, "total_pages", 1),
+ )
+
+ except Exception as e:
+ raise ValidationError("Failed to list MCP servers") from e
+
+ def get(self, server_id: str):
+ """
+ Retrieve detailed information about a specific MCP server/config.
+
+ :param server_id: The unique identifier of the MCP server/config
+ :return: Complete MCP server information
+
+ Example:
+ >>> server = composio.experimental.mcp.get('mcp_12345')
+ >>>
+ >>> print(server['name']) # "My Personal MCP Server"
+ >>> print(server['allowed_tools']) # ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
+ >>> print(server['toolkits']) # ["github", "slack"]
+ >>> print(server['server_instance_count']) # 3
+ """
+ try:
+ response = self._client.mcp.retrieve(server_id)
+
+ return response
+
+ except Exception as e:
+ raise ValidationError(f"Failed to retrieve MCP server {server_id}") from e
+
+ def update(
+ self,
+ server_id: str,
+ name: t.Optional[str] = None,
+ toolkits: t.Optional[t.List[t.Union[MCPToolkitConfig, str]]] = None,
+ manually_manage_connections: t.Optional[bool] = None,
+ allowed_tools: t.Optional[t.List[str]] = None,
+ ):
+ """
+ Update an existing MCP server configuration.
+
+ :param server_id: The unique identifier of the MCP server to update
+ :param name: Optional new name for the MCP server
+ :param toolkits: Optional list of toolkit configurations (strings or objects)
+ :param manually_manage_connections: Optional flag for connection management
+ :param allowed_tools: Optional list of specific tools to enable across all toolkits
+ :return: Updated MCP server information
+
+ Examples:
+ >>> # Update server name only
+ >>> updated_server = composio.experimental.mcp.update(
+ ... 'mcp_12345',
+ ... name='My Updated MCP Server'
+ ... )
+ >>>
+ >>> # Update toolkits and tools
+ >>> server_with_new_tools = composio.experimental.mcp.update(
+ ... 'mcp_12345',
+ ... toolkits=['github', 'slack'],
+ ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
+ ... )
+ >>>
+ >>> # Update with auth configs
+ >>> server_with_auth = composio.experimental.mcp.update(
+ ... 'mcp_12345',
+ ... toolkits=[
+ ... {'toolkit': 'github', 'auth_config_id': 'auth_abc123'},
+ ... {'toolkit': 'slack', 'auth_config_id': 'auth_def456'}
+ ... ],
+ ... allowed_tools=['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
+ ... manually_manage_connections=False
+ ... )
+ """
+ try:
+ update_params = {}
+
+ if name is not None:
+ update_params["name"] = name
+
+ if toolkits is not None:
+ # Normalize toolkits to MCPToolkitConfig format (same as create method)
+ normalized_toolkit_configs = []
+ for toolkit in toolkits:
+ if isinstance(toolkit, str):
+ # Convert string to MCPToolkitConfig
+ normalized_toolkit_configs.append({"toolkit": toolkit})
+ else:
+ # Already MCPToolkitConfig, use as-is
+ normalized_toolkit_configs.append(toolkit)
+
+ # Extract toolkits and prepare for API call
+ toolkit_names = []
+ auth_config_ids = []
+
+ for toolkit_config in normalized_toolkit_configs:
+ if (
+ "toolkit" in toolkit_config
+ and toolkit_config["toolkit"] not in toolkit_names
+ ):
+ toolkit_names.append(toolkit_config["toolkit"])
+
+ if (
+ "auth_config_id" in toolkit_config
+ and toolkit_config["auth_config_id"] not in auth_config_ids
+ ):
+ auth_config_ids.append(toolkit_config["auth_config_id"])
+
+ update_params["toolkits"] = toolkit_names
+ update_params["auth_config_ids"] = auth_config_ids
+
+ if allowed_tools is not None:
+ update_params["custom_tools"] = allowed_tools
+
+ if manually_manage_connections is not None:
+ update_params[
+ "managed_auth_via_composio"
+ ] = not manually_manage_connections
+
+ # Use the MCP update endpoint
+ response = self._client.mcp.update(server_id, **update_params)
+
+ return response
+
+ except Exception as e:
+ raise ValidationError(f"Failed to update MCP server {server_id}") from e
+
+ def delete(self, server_id: str) -> t.Dict[str, t.Any]:
+ """
+ Permanently delete an MCP server configuration.
+
+ :param server_id: The unique identifier of the MCP server to delete
+ :return: Deletion result
+
+ Example:
+ >>> # Delete a server
+ >>> result = composio.experimental.mcp.delete('mcp_12345')
+ >>>
+ >>> if result['deleted']:
+ ... print(f"Server {result['id']} has been successfully deleted")
+ >>> else:
+ ... print(f"Failed to delete server {result['id']}")
+ """
+ try:
+ response = self._client.mcp.delete(server_id)
+
+ return {
+ "id": server_id,
+ "deleted": getattr(response, "deleted", True),
+ }
+
+ except Exception as e:
+ raise ValidationError(f"Failed to delete MCP server {server_id}") from e
+
+ def generate(
+ self,
+ user_id: str,
+ mcp_config_id: str,
+ manually_manage_connections: t.Optional[bool] = None,
+ ) -> MCPServerInstance:
+ """
+ Get server URLs for an existing MCP server.
+
+ This matches the TypeScript implementation exactly.
+
+ :param user_id: External user ID from your database
+ :param mcp_config_id: MCP configuration ID
+ :param manually_manage_connections: Whether to manually manage connections (optional)
+ :return: MCP server instance
+
+ Example:
+ >>> mcp = composio.experimental.mcp.generate(
+ ... 'user_12345',
+ ... 'mcp_67890',
+ ... manually_manage_connections=False
+ ... )
+ >>>
+ >>> print(mcp['url']) # Server URL for the user
+ >>> print(mcp['allowed_tools']) # Available tools
+ """
+
+ try:
+ # Get server details first (matching TS: this.client.mcp.retrieve)
+ server_details = self._client.mcp.retrieve(mcp_config_id)
+
+ # Generate server URLs (matching TS: this.client.mcp.generate.url)
+ url_response = self._client.mcp.generate.url(
+ mcp_server_id=mcp_config_id,
+ user_ids=[user_id],
+ managed_auth_by_composio=False if manually_manage_connections else True,
+ )
+
+ # Get the generated URL (matching TS: urlResponse.user_ids_url[0])
+ if hasattr(url_response, "user_ids_url") and url_response.user_ids_url:
+ server_url = url_response.user_ids_url[0]
+ else:
+ raise ValidationError("No server URL generated")
+
+ # Create structured server instance (matching TS MCPServerInstance)
+ server_instance: MCPServerInstance = {
+ "id": server_details.id,
+ "name": server_details.name,
+ "type": "streamable_http",
+ "url": server_url,
+ "user_id": user_id,
+ "allowed_tools": getattr(server_details, "allowed_tools", []),
+ "auth_configs": getattr(server_details, "auth_config_ids", []),
+ }
+
+ return server_instance
+
+ except Exception as e:
+ if isinstance(e, ValidationError):
+ raise
+ raise ValidationError("Failed to parse MCP server instance") from e
diff --git a/python/composio/core/models/tool_router.py b/python/composio/core/models/tool_router.py
new file mode 100644
index 000000000..f534edf23
--- /dev/null
+++ b/python/composio/core/models/tool_router.py
@@ -0,0 +1,110 @@
+"""
+ToolRouter module for Composio SDK.
+
+This module provides tool routing session management with direct parameter usage,
+following Python conventions and avoiding unnecessary data transformations.
+"""
+
+from __future__ import annotations
+
+import typing as t
+
+import typing_extensions as te
+
+from composio.client import HttpClient
+from composio.core.models.base import Resource
+from composio.core.types import MCPToolkitConfig
+from composio.exceptions import ValidationError
+
+
+# Data Types
+
+
+class ToolRouterSession(te.TypedDict):
+ """Tool router session response."""
+
+ session_id: str # Unique session identifier
+ url: str # Chat session MCP URL
+
+
+class ToolRouter(Resource):
+ """
+ ToolRouter class for managing tool routing sessions.
+
+ Provides functionality to create sessions that route tools through
+ the Composio platform with proper authentication and configuration.
+ """
+
+ def __init__(self, client: HttpClient):
+ """
+ Initialize ToolRouter instance.
+
+ :param client: HTTP client for API calls
+ """
+ super().__init__(client)
+
+ def create_session(
+ self,
+ user_id: str,
+ toolkits: t.Optional[t.List[t.Union[MCPToolkitConfig, str]]] = None,
+ manually_manage_connections: t.Optional[bool] = None,
+ ) -> ToolRouterSession:
+ """
+ Create a new tool router session for a user.
+
+ :param user_id: The user ID to create the session for
+ :param toolkits: List of toolkit configurations (strings or objects)
+ :param manually_manage_connections: Whether to manually manage connections
+ :return: Tool router session with session_id and url
+
+ Examples:
+ >>> # Simple usage with toolkit names
+ >>> session = composio.experimental.tool_router.create_session(
+ ... 'user_123',
+ ... toolkits=['github', 'slack']
+ ... )
+ >>>
+ >>> # With auth configs
+ >>> session = composio.experimental.tool_router.create_session(
+ ... 'user_123',
+ ... toolkits=[
+ ... {'toolkit': 'github', 'auth_config_id': 'ac_123'},
+ ... 'hackernews'
+ ... ],
+ ... manually_manage_connections=False
+ ... )
+ >>>
+ >>> # Access session details
+ >>> print(session['session_id'])
+ >>> print(session['url'])
+ """
+ try:
+ # Normalize toolkits to the format expected by the API
+ toolkit_configs = []
+ if toolkits:
+ for toolkit in toolkits:
+ if isinstance(toolkit, str):
+ # Convert string to toolkit config
+ toolkit_configs.append({"toolkit": toolkit})
+ else:
+ # Already a config object, use as-is
+ toolkit_configs.append(toolkit)
+
+ # Create session using the tool router API
+ session = self._client.tool_router.create_session(
+ user_id=user_id,
+ config={
+ "toolkits": toolkit_configs,
+ "manually_manage_connections": manually_manage_connections,
+ },
+ )
+
+ # Return the session response directly (no unnecessary transformations)
+ return ToolRouterSession(
+ session_id=session.session_id, url=session.chat_session_mcp_url
+ )
+
+ except Exception as e:
+ raise ValidationError(
+ f"Failed to create tool router session for user {user_id}"
+ ) from e
diff --git a/python/composio/core/types.py b/python/composio/core/types.py
index d6adc8e78..861c9c3f8 100644
--- a/python/composio/core/types.py
+++ b/python/composio/core/types.py
@@ -12,9 +12,21 @@ ToolkitVersionParam = t.Union[
str, ToolkitVersions, None
] # String can be any global version
+
+# Shared types for MCP and ToolRouter
+class MCPToolkitConfig(te.TypedDict):
+ """Configuration for a single toolkit in MCP server or ToolRouter session."""
+
+ toolkit: te.NotRequired[str] # e.g., "github", "slack", "composio_search"
+ auth_config_id: te.NotRequired[
+ str
+ ] # Auth configuration ID (for toolkits requiring auth)
+
+
__all__ = [
"ToolkitLatestVersion",
"ToolkitVersion",
"ToolkitVersions",
"ToolkitVersionParam",
+ "MCPToolkitConfig",
]
diff --git a/python/composio/sdk.py b/python/composio/sdk.py
index 41ddd243d..c84dcf857 100644
--- a/python/composio/sdk.py
+++ b/python/composio/sdk.py
@@ -15,6 +15,8 @@ from composio.core.models import (
Triggers,
)
from composio.core.models.base import allow_tracking
+from composio.core.models.mcp import MCP
+from composio.core.models.tool_router import ToolRouter
from composio.core.provider import TProvider
from composio.core.provider._openai import OpenAIProvider
from composio.core.types import ToolkitVersionParam
@@ -35,12 +37,25 @@ class SDKConfig(te.TypedDict):
toolkit_versions: te.NotRequired[ToolkitVersionParam]
+class ExperimentalNamespace:
+ """Namespace for experimental Composio features."""
+
+ def __init__(self, tool_router: ToolRouter):
+ """
+ Initialize experimental namespace.
+
+ :param tool_router: Experimental ToolRouter instance
+ """
+ self.tool_router = tool_router
+
+
class Composio(t.Generic[TProvider], WithLogger):
"""
Composio SDK for Python.
"""
tools: Tools[TProvider]
+ experimental: ExperimentalNamespace[TProvider]
def __init__(
self,
@@ -89,6 +104,12 @@ class Composio(t.Generic[TProvider], WithLogger):
self.triggers = Triggers(client=self._client)
self.auth_configs = AuthConfigs(client=self._client)
self.connected_accounts = ConnectedAccounts(client=self._client)
+ self.mcp = MCP(client=self._client)
+
+ # Initialize experimental features
+ self.experimental = ExperimentalNamespace(
+ tool_router=ToolRouter(client=self._client),
+ )
@property
def client(self):
diff --git a/python/examples/mcp.py b/python/examples/mcp.py
new file mode 100644
index 000000000..9052ddc65
--- /dev/null
+++ b/python/examples/mcp.py
@@ -0,0 +1,31 @@
+import asyncio
+from composio import Composio
+from langchain_mcp_adapters.client import MultiServerMCPClient
+from langgraph.prebuilt import create_react_agent
+
+composio = Composio()
+
+mcp_config = composio.mcp.create(
+ name="langchain-slack-mcp",
+ toolkits=[{"toolkit": "slack", "auth_config_id": "<auth-config-id>"}],
+)
+
+mcp_server = mcp_config.generate(user_id='<user-id>')
+
+client = MultiServerMCPClient(
+ {
+ "composio": {
+ "url": mcp_server["url"],
+ "transport": "streamable_http",
+ }
+ }
+)
+
+async def langchain_mcp(message: str):
+ tools = await client.get_tools()
+ agent = create_react_agent("openai:gpt-4.1", tools)
+ response = await agent.ainvoke({"messages": message})
+ return response
+
+mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))
+
diff --git a/python/providers/anthropic/pyproject.toml b/python/providers/anthropic/pyproject.toml
index 8cbc6083e..0393b959e 100644
--- a/python/providers/anthropic/pyproject.toml
+++ b/python/providers/anthropic/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-anthropic"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your Anthropic LLMs."
readme = "README.md"
requires-python = ">=3.10,<4"
diff --git a/python/providers/anthropic/setup.py b/python/providers/anthropic/setup.py
index 038f441d9..7368a8231 100644
--- a/python/providers/anthropic/setup.py
+++ b/python/providers/anthropic/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_anthropic",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Anthropic LLMs.",
diff --git a/python/providers/autogen/pyproject.toml b/python/providers/autogen/pyproject.toml
index 3f08d687f..0642b5e76 100644
--- a/python/providers/autogen/pyproject.toml
+++ b/python/providers/autogen/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-autogen"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your autogen agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/autogen/setup.py b/python/providers/autogen/setup.py
index d9677f14f..9726307f1 100644
--- a/python/providers/autogen/setup.py
+++ b/python/providers/autogen/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_autogen",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Autogen agent.",
diff --git a/python/providers/crewai/pyproject.toml b/python/providers/crewai/pyproject.toml
index 7ee0b035b..f0df2065d 100644
--- a/python/providers/crewai/pyproject.toml
+++ b/python/providers/crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-crewai"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your CrewAI agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/crewai/setup.py b/python/providers/crewai/setup.py
index 41ba5576a..ee8cf24bf 100644
--- a/python/providers/crewai/setup.py
+++ b/python/providers/crewai/setup.py
@@ -6,7 +6,7 @@ from setuptools import setup
setup(
name="composio_crewai",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your CrewAI agent.",
diff --git a/python/providers/gemini/pyproject.toml b/python/providers/gemini/pyproject.toml
index 9c28a8944..c74fc868a 100644
--- a/python/providers/gemini/pyproject.toml
+++ b/python/providers/gemini/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-gemini"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your Gemini agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/gemini/setup.py b/python/providers/gemini/setup.py
index b7a0036d4..a6d046af9 100644
--- a/python/providers/gemini/setup.py
+++ b/python/providers/gemini/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_gemini",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Gemini agent.",
diff --git a/python/providers/google/pyproject.toml b/python/providers/google/pyproject.toml
index 578e624a3..b086dc4d4 100644
--- a/python/providers/google/pyproject.toml
+++ b/python/providers/google/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-google"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/google/setup.py b/python/providers/google/setup.py
index 8172456b1..1669cab83 100644
--- a/python/providers/google/setup.py
+++ b/python/providers/google/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_google",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
diff --git a/python/providers/google_adk/pyproject.toml b/python/providers/google_adk/pyproject.toml
index 773327ba8..5f8c5bcef 100644
--- a/python/providers/google_adk/pyproject.toml
+++ b/python/providers/google_adk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-google-adk"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your Google AI Python Gemini model."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/google_adk/setup.py b/python/providers/google_adk/setup.py
index 5b861a525..386ed397f 100644
--- a/python/providers/google_adk/setup.py
+++ b/python/providers/google_adk/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_google_adk",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Google AI Python Gemini model.",
diff --git a/python/providers/langchain/pyproject.toml b/python/providers/langchain/pyproject.toml
index 3347aa6c4..9b7734470 100644
--- a/python/providers/langchain/pyproject.toml
+++ b/python/providers/langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-langchain"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your Langchain agent."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/langchain/setup.py b/python/providers/langchain/setup.py
index b96418cdc..0854aba71 100644
--- a/python/providers/langchain/setup.py
+++ b/python/providers/langchain/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_langchain",
- version="0.8.13",
+ version="0.8.14",
author="composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your Langchain agent.",
diff --git a/python/providers/langgraph/pyproject.toml b/python/providers/langgraph/pyproject.toml
index a0bb382d4..195aaacda 100644
--- a/python/providers/langgraph/pyproject.toml
+++ b/python/providers/langgraph/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-langgraph"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get array of tools with LangGraph Agent Workflows."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/langgraph/setup.py b/python/providers/langgraph/setup.py
index 3eb0efda2..a3b0ae34a 100644
--- a/python/providers/langgraph/setup.py
+++ b/python/providers/langgraph/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_langgraph",
- version="0.8.13",
+ version="0.8.14",
author="composio",
author_email="[email protected]",
description="Use Composio to get array of tools with LangGraph Agent Workflows",
diff --git a/python/providers/llamaindex/pyproject.toml b/python/providers/llamaindex/pyproject.toml
index 0aea1ce86..d4419e5c2 100644
--- a/python/providers/llamaindex/pyproject.toml
+++ b/python/providers/llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-llamaindex"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get array of tools with LlamaIndex Agent Workflows."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/llamaindex/setup.py b/python/providers/llamaindex/setup.py
index 71634611b..48303d600 100644
--- a/python/providers/llamaindex/setup.py
+++ b/python/providers/llamaindex/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_llamaindex",
- version="0.8.13",
+ version="0.8.14",
author="composio",
author_email="[email protected]",
description="Use Composio to get array of tools with LlamaIndex Agent Workflows",
diff --git a/python/providers/openai/pyproject.toml b/python/providers/openai/pyproject.toml
index 870570d7e..658dc0ed9 100644
--- a/python/providers/openai/pyproject.toml
+++ b/python/providers/openai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-openai"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get an array of tools with your OpenAI Function Call."
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/openai/setup.py b/python/providers/openai/setup.py
index f78c1a460..4732c463e 100644
--- a/python/providers/openai/setup.py
+++ b/python/providers/openai/setup.py
@@ -8,7 +8,7 @@ from setuptools import setup
setup(
name="composio_openai",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get an array of tools with your OpenAI Function Call.",
diff --git a/python/providers/openai_agents/pyproject.toml b/python/providers/openai_agents/pyproject.toml
index be73cafec..c419495b0 100644
--- a/python/providers/openai_agents/pyproject.toml
+++ b/python/providers/openai_agents/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio-openai-agents"
-version = "0.8.13"
+version = "0.8.14"
description = "Use Composio to get array of strongly typed tools for OpenAI Agents"
readme = "README.md"
requires-python = ">=3.9,<4"
diff --git a/python/providers/openai_agents/setup.py b/python/providers/openai_agents/setup.py
index c2342c0cd..9e2805bde 100644
--- a/python/providers/openai_agents/setup.py
+++ b/python/providers/openai_agents/setup.py
@@ -8,7 +8,7 @@ from setuptools import find_packages, setup
setup(
name="composio_openai_agents",
- version="0.8.13",
+ version="0.8.14",
author="Composio",
author_email="[email protected]",
description="Use Composio to get array of strongly typed tools for OpenAI Agents",
diff --git a/python/pyproject.toml b/python/pyproject.toml
index c94d5b348..a75410a49 100644
--- a/python/pyproject.toml
+++ b/python/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "composio"
-version = "0.8.15"
+version = "0.8.16"
description = "SDK for integrating Composio with your applications."
readme = "README.md"
requires-python = ">=3.10,<4"
diff --git a/python/tests/test_core_types.py b/python/tests/test_core_types.py
index 0827d167c..2a412823d 100644
--- a/python/tests/test_core_types.py
+++ b/python/tests/test_core_types.py
@@ -56,6 +56,7 @@ class TestCoreTypes:
from composio.core.types import __all__
expected_exports = {
+ "MCPToolkitConfig",
"ToolkitLatestVersion",
"ToolkitVersion",
"ToolkitVersions",
diff --git a/ts/docs/README.md b/ts/docs/README.md
index f2eaaab03..b3b0e08f6 100644
--- a/ts/docs/README.md
+++ b/ts/docs/README.md
@@ -43,6 +43,7 @@ The Composio SDK is built around several key concepts:
- **Auth Configs**: Authentication configurations for external services
- **Providers**: Adapters for AI services that can use tools (e.g., OpenAI)
- **Custom Tools**: Tools you can create and define yourself
+- **MCP**: Create and manage MCP Servers and clients
Check out the [Core Concepts](./core-concepts.md) documentation for more detailed information.
@@ -88,6 +89,8 @@ The complete API reference documentation is available here:
- [Auth Configs](./api/auth-configs.md)
- [Providers](./api/providers.md)
- [Custom Tools](./api/custom-tools.md)
+- [MCP](./api/mcp.md)
+- [ToolRouter (experimental)](./api/tool-router.experimental.md)
## Providers
diff --git a/ts/docs/api/experimental-mcp.md b/ts/docs/api/experimental-mcp.md
index acc93b366..9e85fb8bc 100644
--- a/ts/docs/api/experimental-mcp.md
+++ b/ts/docs/api/experimental-mcp.md
@@ -1,33 +1,27 @@
-# Experimental MCP (Model Control Protocol) API
+# MCP (Model Control Protocol) API
-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.
+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.
## Overview
-The experimental MCP API introduces two key components:
+Key benefits of the MCP API:
-1. **`experimental.mcp`** - Enhanced MCP server operations with provider-specific response formatting
-2. **`experimental.mcpConfig`** - Simplified MCP configuration management
-
-Key benefits of the experimental API:
-- **Provider-specific optimizations**: Automatic response formatting for different AI frameworks
-- **Simplified configuration**: Streamlined server creation and management
-- **Enhanced type safety**: Better TypeScript support with provider-specific return types
-- **Framework integration**: Direct compatibility with popular AI frameworks like Anthropic, OpenAI, Vercel AI, Google Gemini, and Mastra
+- **Flexible configuration**: Support for multiple toolkits and authentication methods
+- **User-specific servers**: Generate unique MCP server URLs for individual users
+- **Comprehensive management**: Full CRUD operations for MCP server configurations
+- **Authentication flexibility**: Choose between manual account management or Composio-managed authentication
## Getting Started
-### Enabling Experimental MCP
+### Using MCP API
-The experimental MCP features are available by default. Simply initialize Composio with your chosen provider:
+The MCP features are available by default when you initialize Composio:
```typescript
import { Composio } from '@composio/core';
-import { AnthropicProvider } from '@composio/anthropic';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider(),
});
```
@@ -35,466 +29,401 @@ const composio = new Composio({
```typescript
// 1. Create MCP configuration
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "my-server-name",
- [
- {
- authConfigId: "ac_your_auth_config",
- allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
- }
- ],
- { isChatAuth: true }
-);
+const mcpConfig = await composio.mcp.create('my-server-name', {
+ toolkits: [{ toolkit: 'github', authConfigId: 'ac_233434343' }],
+ allowedTools: ['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS'],
+ manuallyManageConnections: false,
+});
-// 2. Get server URLs for a user
-const servers = await composio.experimental.mcp.getServer(
- "user123",
- mcpConfig.id,
- { limitTools: ["GMAIL_FETCH_EMAILS"] }
-);
+// 2. Generate server instance for a user
+const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
-// 3. Use with your AI framework (provider-specific format)
-// servers is automatically formatted for your chosen provider
+// 3. Use the server URL with any MCP client
+const mcpUrl = serverInstance.url;
```
## API Reference
-### experimental.mcpConfig
-
-The `mcpConfig` class provides simplified MCP server configuration management.
+### composio.mcp
-#### create(name, serverConfig, options)
+#### create(name, mcpConfig)
Creates a new MCP server configuration with the specified toolkit settings.
```typescript
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "gmail-assistant",
- [
- {
- authConfigId: "ac_gmail_config",
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
- },
- {
- authConfigId: "ac_slack_config",
- allowedTools: ["SLACK_SEND_MESSAGE"]
- }
+const mcpConfig = await composio.mcp.create('gmail-assistant', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'ac_gmail_config' },
+ { toolkit: 'slack', authConfigId: 'ac_slack_config' },
],
- {
- isChatAuth: true // Use Composio-managed authentication
- }
-);
+ allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'SLACK_SEND_MESSAGE'],
+ manuallyManageConnections: false,
+});
+
+// Alternative with string toolkit names
+const mcpConfig = await composio.mcp.create('simple-server', {
+ toolkits: ['github', 'slack'],
+ allowedTools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
+ manuallyManageConnections: false,
+});
```
**Parameters:**
- `name` (string): Unique name for the MCP server configuration
-- `serverConfig` (Array): Array of authentication and tool configurations
- - `authConfigId`: The authentication configuration ID to use
- - `allowedTools`: Array of specific tool IDs to expose through this configuration
-- `options` (object): Configuration options
- - `isChatAuth` (boolean, optional): Whether to use Composio-managed authentication
+- `mcpConfig` (object): MCP configuration parameters
+ - `toolkits` (Array): Array of toolkit configurations - can be strings or objects
+ - As string: Just the toolkit name (e.g., "github", "slack")
+ - As object: `{ toolkit?: string, authConfigId?: string }`
+ - `allowedTools` (string[], optional): Array of specific tool IDs to expose
+ - `manuallyManageConnections` (boolean, optional): Whether to manually manage account connections. If false, Composio will inject account management tools. Defaults to false.
+
+**Returns:** `Promise<MCPConfigCreateResponse>` - Created server details including:
-**Returns:** `Promise<McpServerCreateResponse>` - Created server details including:
- `id`: Server configuration UUID
- `name`: Server name
-- `toolkits`: Array of toolkit names
-- `getServer`: Convenience method to get server URLs
-
-#### getByName(configName)
-
-Retrieves an existing MCP configuration by its name.
-
-```typescript
-const existingConfig = await composio.experimental.mcpConfig.getByName('gmail-assistant');
-```
+- `allowedTools`: Array of allowed tool IDs
+- `authConfigIds`: Array of auth configuration IDs
+- `commands`: Setup commands for different MCP clients (Claude, Cursor, Windsurf)
+- `MCPUrl`: Base MCP server URL
+- `generate`: Convenience method to generate user-specific server instances
-**Parameters:**
-- `configName` (string): Name of the MCP configuration to retrieve
-
-**Returns:** `Promise<McpRetrieveResponse>` - Configuration details
-
-### experimental.mcp
-
-The experimental MCP class provides enhanced server operations with provider-specific response formatting.
-
-#### getServer(userId, mcpConfigurationId, options?)
+#### generate(userId, mcpConfigurationId, options?)
-Retrieves MCP server URLs formatted specifically for your chosen provider.
+Generates a user-specific MCP server instance with a unique URL.
```typescript
-// Returns provider-specific format
-const servers = await composio.experimental.mcp.getServer(
- "user123",
- "mcp_config_uuid",
- {
- limitTools: ["GMAIL_FETCH_EMAILS"],
- isChatAuth: true
- }
-);
+const serverInstance = await composio.mcp.generate('user123', 'mcp_config_uuid', {
+ manuallyManageConnections: false,
+});
```
**Parameters:**
-- `userId` (string): ID of the user to generate server URLs for
+- `userId` (string): ID of the user to generate server instance for
- `mcpConfigurationId` (string): UUID of the MCP configuration
- `options` (object, optional): Additional server options
- - `limitTools` (string[]): Subset of tools to expose (from the configuration)
- - `isChatAuth` (boolean): Override authentication method
+ - `manuallyManageConnections` (boolean): Override authentication method
-**Returns:** Provider-specific response format (see [Provider Integration](#provider-integration))
+**Returns:** `Promise<MCPServerInstance>` - Server instance details including:
-#### getRawMCPServer(userId, mcpConfigurationId, options?)
-
-Returns the raw MCP server response without provider-specific formatting.
-
-```typescript
-const rawServer = await composio.experimental.mcp.getRawMCPServer(
- "user123",
- "mcp_config_uuid"
-);
-```
-
-**Parameters:** Same as `getServer()`
-
-**Returns:** Raw MCP server response
-
-## Provider Integration
-
-The experimental MCP API automatically formats responses based on your chosen provider:
+- `id`: Server configuration ID
+- `name`: Server name
+- `type`: Connection type (always 'streamable_http')
+- `url`: User-specific MCP server URL
+- `userId`: Associated user ID
+- `allowedTools`: Array of available tool IDs
+- `authConfigs`: Array of auth configuration IDs
-### Anthropic Provider
+#### list(options)
-Returns an array of server configurations compatible with Anthropic's MCP client:
+Lists MCP server configurations with optional filtering and pagination.
```typescript
-import { AnthropicProvider } from '@composio/anthropic';
+// List all MCP servers
+const allServers = await composio.mcp.list({});
-const composio = new Composio({
- provider: new AnthropicProvider(),
+// List with pagination
+const pagedServers = await composio.mcp.list({
+ page: 2,
+ limit: 5
});
-const servers = await composio.experimental.mcp.getServer(userId, configId);
-// Returns: McpServerUrlInfo[]
-// [
-// {
-// url: new URL("https://mcp.composio.dev/..."),
-// name: "gmail-assistant-user123",
-// toolkit: "gmail"
-// }
-// ]
+// Filter by toolkit
+const githubServers = await composio.mcp.list({
+ toolkits: ['github', 'slack']
+});
-// Use with Anthropic Claude
-const stream = anthropic.beta.messages.stream({
- model: 'claude-4-sonnet-20250514',
- mcp_servers: servers,
- messages: [...],
- betas: ['mcp-client-2025-04-04'],
+// Filter by name
+const namedServers = await composio.mcp.list({
+ name: 'personal'
});
```
-### Google Gemini Provider
+**Parameters:**
-Returns a URL string for use with Google's MCP integration:
+- `options` (object): Filtering and pagination options
+ - `page` (number, optional): Page number for pagination (1-based, defaults to 1)
+ - `limit` (number, optional): Maximum items per page (defaults to 10)
+ - `toolkits` (string[], optional): Filter by toolkit names
+ - `authConfigs` (string[], optional): Filter by auth configuration IDs
+ - `name` (string, optional): Filter by server name (partial match)
-```typescript
-import { GoogleProvider } from '@composio/google';
-import { GoogleGenAI, mcpToTool } from '@google/genai';
+**Returns:** `Promise<MCPListResponse>` - Paginated list with metadata:
-const composio = new Composio({
- provider: new GoogleProvider(),
-});
+- `items`: Array of MCP server configurations
+- `currentPage`: Current page number
+- `totalPages`: Total number of pages
-const url = await composio.experimental.mcp.getServer(userId, configId);
-// Returns: string (URL)
+#### get(serverId)
-// Create MCP client and tools
-const serverParams = new SSEClientTransport(url);
-const mcpClient = new MCPClient({
- name: 'composio-mcp-client',
- version: '1.0.0',
-});
+Retrieves detailed information about a specific MCP server.
-await mcpClient.connect(serverParams);
-const tools = [mcpToTool(mcpClient)];
+```typescript
+const server = await composio.mcp.get("mcp_12345");
-// Use with Google Gemini
-const gemini = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
-const stream = await gemini.models.generateContentStream({
- model: 'gemini-2.5-flash',
- contents: 'Your prompt here',
- config: { tools },
-});
+console.log(server.name); // "My Personal MCP Server"
+console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
+console.log(server.toolkits); // ["github", "slack"]
+console.log(server.serverInstanceCount); // 3
+
+// Access setup commands for different clients
+console.log(server.commands.claude); // Claude setup command
+console.log(server.commands.cursor); // Cursor setup command
+console.log(server.commands.windsurf); // Windsurf setup command
```
-### Mastra Provider
+**Parameters:**
-Returns a key-value mapping of server configurations:
+- `serverId` (string): The unique identifier of the MCP server
-```typescript
-import { MastraProvider } from '@composio/mastra';
-import { MCPClient as MastraMCPClient } from '@mastra/mcp';
+**Returns:** `Promise<MCPItem>` - Complete server details including configuration, tools, and metadata
-const composio = new Composio({
- provider: new MastraProvider(),
-});
+#### update(serverId, config)
-const servers = await composio.experimental.mcp.getServer(userId, configId);
-// Returns: Record<string, { url: string }>
-// {
-// "server-0": { url: "https://mcp.composio.dev/..." }
-// }
+Updates an existing MCP server configuration.
-// Use with Mastra
-const mcpClient = new MastraMCPClient({ servers });
-const tools = await mcpClient.getTools();
+```typescript
+// Update server name only
+const updatedServer = await composio.mcp.update("mcp_12345", {
+ name: "My Updated MCP Server"
+});
-const agent = new MastraAgent({
- name: 'Gmail Assistant',
- model: openai('gpt-4o-mini'),
- tools: wrapTools(servers, tools),
+// Update toolkits and tools
+const serverWithNewTools = await composio.mcp.update("mcp_12345", {
+ toolkits: [
+ {
+ toolkit: "github",
+ authConfigId: "auth_abc123"
+ },
+ {
+ toolkit: "slack",
+ authConfigId: "auth_xyz789"
+ }
+ ],
+ allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS", "SLACK_SEND_MESSAGE"]
});
```
-### Vercel AI Provider
+**Parameters:**
-Returns a URL string for use with Vercel AI's MCP client:
+- `serverId` (string): The unique identifier of the MCP server to update
+- `config` (object): Update configuration parameters
+ - `name` (string, optional): New name for the MCP server
+ - `toolkits` (Array, optional): Updated toolkit configurations
+ - `allowedTools` (string[], optional): Updated list of allowed tools
+ - `manuallyManageConnections` (boolean, optional): Updated connection management setting
-```typescript
-import { VercelProvider } from '@composio/vercel';
-import { experimental_createMCPClient as createMCPClient, streamText } from 'ai';
+**Returns:** `Promise<MCPItem>` - Updated MCP server configuration
-const composio = new Composio({
- provider: new VercelProvider(),
-});
-
-const url = await composio.experimental.mcp.getServer(userId, configId);
-// Returns: string (URL)
+#### delete(serverId)
-// Create Vercel AI MCP client
-const serverParams = new SSEClientTransport(url);
-const mcpClient = await createMCPClient({
- name: 'composio-mcp-client',
- transport: serverParams,
-});
+Permanently deletes an MCP server configuration.
-const tools = await mcpClient.tools();
+```typescript
+const result = await composio.mcp.delete("mcp_12345");
-// Use with Vercel AI
-const stream = streamText({
- model: openai('gpt-4o-mini'),
- messages: [...],
- tools,
-});
+if (result.deleted) {
+ console.log(`Server ${result.id} has been successfully deleted`);
+}
```
-### OpenAI Provider
-
-Returns an array of server configurations:
+**Parameters:**
-```typescript
-import { OpenAIProvider } from '@composio/openai';
+- `serverId` (string): The unique identifier of the MCP server to delete
-const composio = new Composio({
- provider: new OpenAIProvider(),
-});
+**Returns:** `Promise<{id: string; deleted: boolean}>` - Deletion confirmation
-const servers = await composio.experimental.mcp.getServer(userId, configId);
-// Returns: McpServerUrlInfo[]
-```
+**⚠️ Warning:** This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
## Complete Examples
-### Anthropic Claude Example
+### Basic MCP Server Setup
```typescript
import { Composio } from '@composio/core';
-import { AnthropicProvider } from '@composio/anthropic';
-import Anthropic from '@anthropic-ai/sdk';
-// 1. Initialize Composio with experimental MCP
+// 1. Initialize Composio
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider({ cacheTools: true }),
});
// 2. Create MCP configuration
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `gmail-assistant-${Date.now()}`,
- [
- {
- authConfigId: "ac_your_gmail_config",
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
- }
- ],
- { isChatAuth: true }
-);
-
-// 3. Get server URLs for connected account
-const servers = await composio.experimental.mcp.getServer(
- "user123",
- mcpConfig.id,
- { limitTools: ["GMAIL_FETCH_EMAILS"] }
-);
-
-// 4. Use with Anthropic Claude
-const anthropic = new Anthropic({
- apiKey: process.env.ANTHROPIC_API_KEY,
+const mcpConfig = await composio.mcp.create('gmail-assistant', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_your_gmail_config' }],
+ allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
+ manuallyManageConnections: false,
});
-const stream = anthropic.beta.messages.stream({
- model: 'claude-4-sonnet-20250514',
- max_tokens: 64_000,
- mcp_servers: servers,
- messages: [
- {
- role: 'user',
- content: 'Fetch my latest 3 emails and summarize them',
- },
- ],
- betas: ['mcp-client-2025-04-04'],
-});
+console.log('MCP Configuration created:', mcpConfig.id);
+console.log('Setup commands:');
+console.log('Claude:', mcpConfig.commands.claude);
+console.log('Cursor:', mcpConfig.commands.cursor);
+console.log('Windsurf:', mcpConfig.commands.windsurf);
-for await (const event of stream) {
- if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
- process.stdout.write(event.delta.text);
- }
-}
+// 3. Generate server instance for a user
+const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
+
+console.log('MCP Server URL for user123:', serverInstance.url);
+console.log('Available tools:', serverInstance.allowedTools);
```
-### Google Gemini Example
+### Using with Generic MCP Client
```typescript
import { Composio } from '@composio/core';
-import { GoogleProvider } from '@composio/google';
-import { GoogleGenAI, mcpToTool } from '@google/genai';
import { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
-// 1. Initialize Composio
+// 1. Initialize Composio and create MCP configuration
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new GoogleProvider(),
});
-// 2. Create MCP configuration
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `gmail-assistant-${Date.now()}`,
- [
- {
- authConfigId: "ac_your_gmail_config",
- allowedTools: ["GMAIL_FETCH_EMAILS"]
- }
+const mcpConfig = await composio.mcp.create('multi-toolkit-assistant', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'ac_gmail_config' },
+ { toolkit: 'github', authConfigId: 'ac_github_config' },
],
- { isChatAuth: true }
-);
+ allowedTools: [
+ 'GMAIL_FETCH_EMAILS',
+ 'GMAIL_SEND_EMAIL',
+ 'GITHUB_CREATE_ISSUE',
+ 'GITHUB_LIST_REPOS'
+ ],
+ manuallyManageConnections: false,
+});
-// 3. Get server URL
-const url = await composio.experimental.mcp.getServer(
- "user123",
- mcpConfig.id
-);
+// 2. Generate server instance for a specific user
+const serverInstance = await composio.mcp.generate('user456', mcpConfig.id);
-// 4. Create MCP client
-const serverParams = new SSEClientTransport(url);
+// 3. Create MCP client connection
+const transport = new SSEClientTransport(new URL(serverInstance.url));
const mcpClient = new MCPClient({
name: 'composio-mcp-client',
version: '1.0.0',
});
-await mcpClient.connect(serverParams);
-const tools = [mcpToTool(mcpClient)];
+await mcpClient.connect(transport);
-// 5. Use with Google Gemini
-const gemini = new GoogleGenAI({
- apiKey: process.env.GEMINI_API_KEY,
-});
+// 4. List available tools
+const { tools } = await mcpClient.listTools();
+console.log('Available tools:', tools.map(t => t.name));
-const stream = await gemini.models.generateContentStream({
- model: 'gemini-2.5-flash',
- contents: 'Fetch my latest 2 emails and provide a summary',
- config: { tools },
+// 5. Call a tool
+const result = await mcpClient.callTool({
+ name: 'GMAIL_FETCH_EMAILS',
+ arguments: {
+ limit: 5
+ }
});
-for await (const chunk of stream) {
- console.log(chunk.text);
-}
+console.log('Email fetch result:', result);
+// 6. Clean up
await mcpClient.close();
```
-### Mastra Example
+### Managing Multiple Servers
```typescript
-import { openai } from '@ai-sdk/openai';
import { Composio } from '@composio/core';
-import { MastraProvider } from '@composio/mastra';
-import { MCPClient as MastraMCPClient } from '@mastra/mcp';
-import { Agent as MastraAgent } from '@mastra/core/agent';
-// Helper function to remove server prefixes from tool names
-function wrapTools(servers: Record<string, any>, tools: Record<string, any>): Record<string, any> {
- const prefixes = Object.keys(servers);
-
- function removePrefix(str: string): string {
- for (const prefix of prefixes) {
- if (str.startsWith(prefix)) {
- return str.slice(prefix.length + 1);
- }
- }
- return str;
- }
-
- return Object.fromEntries(
- Object.entries(tools).map(([key, tool]) => {
- return [removePrefix(key), tool] as const;
- })
- );
-}
-
-// 1. Initialize Composio
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new MastraProvider(),
});
-// 2. Create MCP configuration
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `gmail-assistant-${Date.now()}`,
- [
- {
- authConfigId: "ac_your_gmail_config",
- allowedTools: ["GMAIL_FETCH_EMAILS"]
- }
+// Create multiple MCP configurations for different use cases
+const personalConfig = await composio.mcp.create('personal-assistant', {
+ toolkits: ['gmail', 'calendar'],
+ allowedTools: ['GMAIL_FETCH_EMAILS', 'CALENDAR_LIST_EVENTS'],
+ manuallyManageConnections: false,
+});
+
+const workConfig = await composio.mcp.create('work-assistant', {
+ toolkits: [
+ { toolkit: 'github', authConfigId: 'ac_work_github' },
+ { toolkit: 'slack', authConfigId: 'ac_work_slack' },
],
- { isChatAuth: true }
-);
+ allowedTools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
+ manuallyManageConnections: false,
+});
-// 3. Get server URLs
-const servers = await composio.experimental.mcp.getServer(
- "user123",
- mcpConfig.id
-);
+// List all configurations
+const allConfigs = await composio.mcp.list({});
+console.log(`Total configurations: ${allConfigs.items.length}`);
+
+// Generate instances for different users
+const personalInstance = await composio.mcp.generate('user123', personalConfig.id);
+const workInstance = await composio.mcp.generate('user123', workConfig.id);
+
+console.log('Personal MCP URL:', personalInstance.url);
+console.log('Work MCP URL:', workInstance.url);
+
+// Update a configuration
+const updatedConfig = await composio.mcp.update(personalConfig.id, {
+ name: 'Enhanced Personal Assistant',
+ allowedTools: [
+ 'GMAIL_FETCH_EMAILS',
+ 'GMAIL_SEND_EMAIL',
+ 'CALENDAR_LIST_EVENTS',
+ 'CALENDAR_CREATE_EVENT'
+ ]
+});
+
+console.log('Updated configuration:', updatedConfig.name);
+```
+
+### Vercel AI Integration Example
+
+```typescript
+import { Composio } from '@composio/core';
+import { experimental_createMCPClient as createMCPClient, streamText } from 'ai';
+import { openai } from '@ai-sdk/openai';
+import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
+
+// 1. Initialize Composio and create MCP configuration
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+});
+
+const mcpConfig = await composio.mcp.create('ai-assistant', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_gmail_config' }],
+ allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
+ manuallyManageConnections: false,
+});
-// 4. Create Mastra MCP client
-const mcpClient = new MastraMCPClient({ servers });
-const tools = await mcpClient.getTools();
+// 2. Generate server instance
+const serverInstance = await composio.mcp.generate('user789', mcpConfig.id);
-// 5. Create Mastra agent
-const agent = new MastraAgent({
- name: 'Gmail Assistant',
- instructions: 'You are a helpful Gmail assistant.',
+// 3. Create Vercel AI MCP client
+const transport = new SSEClientTransport(new URL(serverInstance.url));
+const mcpClient = await createMCPClient({
+ name: 'composio-mcp-client',
+ transport: transport,
+});
+
+const tools = await mcpClient.tools();
+
+// 4. Use with Vercel AI
+const stream = streamText({
model: openai('gpt-4o-mini'),
- tools: wrapTools(servers, tools),
+ messages: [
+ {
+ role: 'user',
+ content: 'Fetch my latest 3 emails and provide a summary of each one',
+ },
+ ],
+ tools,
});
-// 6. Use the agent
-const response = await agent.generate(
- 'Fetch my latest 2 emails and provide a summary'
-);
-console.log(response.text);
+// 5. Stream the response
+for await (const textPart of stream.textStream) {
+ process.stdout.write(textPart);
+}
-await mcpClient.disconnect();
+// 6. Clean up
+await mcpClient.close();
```
## Configuration Management
@@ -512,16 +441,11 @@ const authConfig = await composio.authConfigs.create({
});
// Use the auth config ID in your MCP configuration
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "gmail-server",
- [
- {
- authConfigId: authConfig.id,
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
- }
- ],
- { isChatAuth: true }
-);
+const mcpConfig = await composio.mcp.create('gmail-server', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: authConfig.id }],
+ allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
+ manuallyManageConnections: false,
+});
```
### Tool Selection
@@ -529,98 +453,153 @@ const mcpConfig = await composio.experimental.mcpConfig.create(
You can specify exactly which tools to expose through your MCP server:
```typescript
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "multi-toolkit-server",
- [
- {
- authConfigId: "ac_gmail_config",
- allowedTools: [
- "GMAIL_FETCH_EMAILS",
- "GMAIL_SEND_EMAIL",
- "GMAIL_CREATE_DRAFT"
- ]
- },
- {
- authConfigId: "ac_slack_config",
- allowedTools: [
- "SLACK_SEND_MESSAGE",
- "SLACK_LIST_CHANNELS"
- ]
- }
+const mcpConfig = await composio.mcp.create('multi-toolkit-server', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'ac_gmail_config' },
+ { toolkit: 'slack', authConfigId: 'ac_slack_config' },
],
- { isChatAuth: true }
-);
+ allowedTools: [
+ 'GMAIL_FETCH_EMAILS',
+ 'GMAIL_SEND_EMAIL',
+ 'GMAIL_CREATE_DRAFT',
+ 'SLACK_SEND_MESSAGE',
+ 'SLACK_LIST_CHANNELS',
+ ],
+ manuallyManageConnections: false,
+});
```
-### Runtime Tool Limiting
+### Flexible Toolkit Configuration
-You can further limit tools when getting server URLs:
+You can configure toolkits in multiple ways:
```typescript
-const servers = await composio.experimental.mcp.getServer(
- "user123",
- mcpConfig.id,
- {
- limitTools: ["GMAIL_FETCH_EMAILS"], // Only expose this tool
- isChatAuth: true
- }
-);
+// Using string array (requires default auth configs)
+const simpleConfig = await composio.mcp.create('simple-server', {
+ toolkits: ['github', 'slack'],
+ allowedTools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'],
+ manuallyManageConnections: false,
+});
+
+// Using mixed configuration
+const mixedConfig = await composio.mcp.create('mixed-server', {
+ toolkits: [
+ 'calendar', // Uses default auth config
+ { toolkit: 'gmail', authConfigId: 'ac_specific_gmail' }, // Uses specific auth config
+ { authConfigId: 'ac_custom_integration' }, // Uses auth config without toolkit name
+ ],
+ manuallyManageConnections: false,
+});
```
## Types
-### MCPServerConfig
+### MCPConfigCreationParams
```typescript
-interface MCPServerConfig {
- authConfigId: string; // Authentication configuration ID
- allowedTools: string[]; // Array of tool IDs to expose
+interface MCPConfigCreationParams {
+ toolkits: Array<string | MCPConfigToolkits>; // Array of toolkit configurations
+ allowedTools?: string[]; // Optional array of specific tool IDs to expose
+ manuallyManageConnections?: boolean; // Whether to manually manage account connections (default: false)
+}
+
+interface MCPConfigToolkits {
+ toolkit?: string; // Toolkit identifier (e.g., "github", "slack")
+ authConfigId?: string; // Authentication configuration ID
}
```
-### MCPConfigOptions
+### MCPConfigCreateResponse
```typescript
-interface MCPConfigOptions {
- isChatAuth?: boolean; // Use Composio-managed authentication
+interface MCPConfigCreateResponse {
+ id: string; // Configuration UUID
+ name: string; // Configuration name
+ allowedTools: string[]; // Array of allowed tool IDs
+ authConfigIds: string[]; // Array of auth configuration IDs
+ commands: {
+ claude: string; // Claude setup command
+ cursor: string; // Cursor setup command
+ windsurf: string; // Windsurf setup command
+ };
+ MCPUrl: string; // Base MCP server URL
+ generate: (userId: string) => Promise<MCPServerInstance>; // Convenience method
}
```
-### McpServerCreateResponse
+### MCPServerInstance
```typescript
-interface McpServerCreateResponse<T> {
- id: string; // Configuration UUID
- name: string; // Configuration name
- toolkits: string[]; // Array of toolkit names
- createdAt?: string; // Creation timestamp
- updatedAt?: string; // Last update timestamp
- getServer: (params: { // Convenience method
- userId?: string;
- limitTools?: string[];
- isChatAuth?: boolean;
- }) => Promise<T>;
+interface MCPServerInstance {
+ id: string; // Server configuration ID
+ name: string; // Server name
+ type: 'streamable_http'; // Connection type
+ url: string; // User-specific MCP server URL
+ userId: string; // Associated user ID
+ allowedTools: string[]; // Array of available tool IDs
+ authConfigs: string[]; // Array of auth configuration IDs
}
```
-### Provider-Specific Response Types
+### MCPListParams
+
+```typescript
+interface MCPListParams {
+ page?: number; // Page number for pagination (1-based, default: 1)
+ limit?: number; // Maximum items per page (default: 10)
+ toolkits?: string[]; // Filter by toolkit names
+ authConfigs?: string[]; // Filter by auth configuration IDs
+ name?: string; // Filter by server name (partial match)
+}
+```
-#### McpServerUrlInfo (Anthropic, OpenAI, etc.)
+### MCPListResponse
```typescript
-interface McpServerUrlInfo {
- url: URL; // MCP server URL
- name: string; // Server instance name
- toolkit?: string; // Associated toolkit
+interface MCPListResponse {
+ items: MCPItem[]; // Array of MCP server configurations
+ currentPage: number; // Current page number
+ totalPages: number; // Total number of pages
}
```
-#### Mastra Server Format
+### MCPItem
```typescript
-type MastraServerFormat = Record<string, {
- url: string; // MCP server URL
-}>;
+interface MCPItem {
+ id: string; // Server configuration ID
+ name: string; // Server name
+ allowedTools: string[]; // Array of allowed tool IDs
+ authConfigIds: string[]; // Array of auth configuration IDs
+ commands: {
+ claude: string; // Claude setup command
+ cursor: string; // Cursor setup command
+ windsurf: string; // Windsurf setup command
+ };
+ MCPUrl: string; // Base MCP server URL
+ toolkitIcons: Record<string, string>; // Toolkit icons mapping
+ serverInstanceCount: number; // Number of active server instances
+ toolkits: string[]; // Array of associated toolkit names
+}
+```
+
+### MCPUpdateParams
+
+```typescript
+interface MCPUpdateParams {
+ name?: string; // Updated server name
+ toolkits?: Array<string | MCPConfigToolkits>; // Updated toolkit configurations
+ allowedTools?: string[]; // Updated array of allowed tools
+ manuallyManageConnections?: boolean; // Updated connection management setting
+}
+```
+
+### MCPGetInstanceParams
+
+```typescript
+interface MCPGetInstanceParams {
+ manuallyManageConnections?: boolean; // Whether to manually manage account connections (default: false)
+}
```
## Best Practices
@@ -631,17 +610,21 @@ Use descriptive names that indicate the purpose and scope:
```typescript
// Good
-await composio.experimental.mcpConfig.create(
+await composio.mcp.create(
"gmail-support-assistant",
- [...],
- { isChatAuth: true }
+ {
+ toolkits: [...],
+ manuallyManageConnections: false
+ }
);
// Avoid
-await composio.experimental.mcpConfig.create(
+await composio.mcp.create(
"config1",
- [...],
- { isChatAuth: true }
+ {
+ toolkits: [...],
+ manuallyManageConnections: false
+ }
);
```
@@ -651,32 +634,18 @@ Be specific about which tools to expose:
```typescript
// Good - specific tools for the use case
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "email-assistant",
- [
- {
- authConfigId: "ac_gmail",
- allowedTools: [
- "GMAIL_FETCH_EMAILS",
- "GMAIL_SEND_EMAIL",
- "GMAIL_CREATE_DRAFT"
- ]
- }
- ],
- { isChatAuth: true }
-);
+const mcpConfig = await composio.mcp.create('email-assistant', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_gmail' }],
+ allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL', 'GMAIL_CREATE_DRAFT'],
+ manuallyManageConnections: false,
+});
// Avoid - exposing unnecessary tools
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "email-assistant",
- [
- {
- authConfigId: "ac_gmail",
- allowedTools: ["*"] // Exposes all tools
- }
- ],
- { isChatAuth: true }
-);
+const mcpConfig = await composio.mcp.create('email-assistant', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_gmail' }],
+ // No allowedTools specified - exposes all tools
+ manuallyManageConnections: false,
+});
```
### 3. Authentication Management
@@ -685,10 +654,12 @@ Use Composio-managed authentication when possible:
```typescript
// Recommended
-const mcpConfig = await composio.experimental.mcpConfig.create(
+const mcpConfig = await composio.mcp.create(
"server-name",
- [...],
- { isChatAuth: true } // Let Composio handle auth
+ {
+ toolkits: [...],
+ manuallyManageConnections: false // Let Composio handle auth
+ }
);
```
@@ -698,18 +669,14 @@ Always handle potential errors:
```typescript
try {
- const mcpConfig = await composio.experimental.mcpConfig.create(
- "server-name",
- serverConfigs,
- { isChatAuth: true }
- );
-
- const servers = await composio.experimental.mcp.getServer(
- userId,
- mcpConfig.id
- );
-
- // Use servers with your AI framework
+ const mcpConfig = await composio.mcp.create('server-name', {
+ toolkits: serverConfigs,
+ manuallyManageConnections: false,
+ });
+
+ const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
+
+ // Use server instance with your MCP client
} catch (error) {
if (error instanceof ValidationError) {
console.error('Configuration error:', error.message);
@@ -727,83 +694,188 @@ Clean up MCP clients when done:
// For generic MCP clients
await mcpClient.close();
-// For Mastra clients
-await mcpClient.disconnect();
+// For Vercel AI MCP clients
+await mcpClient.close();
+```
+
+### 6. Server Instance Management
+
+Generate server instances per user to maintain proper isolation:
+
+```typescript
+// Good - separate instances for different users
+const userAInstance = await composio.mcp.generate('userA', mcpConfig.id);
+const userBInstance = await composio.mcp.generate('userB', mcpConfig.id);
+
+// Each user gets their own isolated MCP server URL
+console.log('User A MCP URL:', userAInstance.url);
+console.log('User B MCP URL:', userBInstance.url);
+```
+
+### 7. Pagination for Large Lists
+
+Use pagination when listing many MCP configurations:
+
+```typescript
+// Good - paginate through results
+let currentPage = 1;
+let hasMore = true;
+
+while (hasMore) {
+ const result = await composio.mcp.list({
+ page: currentPage,
+ limit: 20
+ });
+
+ // Process result.items
+ console.log(`Page ${currentPage}: ${result.items.length} items`);
+
+ hasMore = currentPage < result.totalPages;
+ currentPage++;
+}
```
-## Migration from Standard MCP
+## Migration from Deprecated MCP API
-If you're using the standard MCP API, here's how to migrate:
+If you're using the deprecated MCP API, here's how to migrate:
-### Before (Standard MCP)
+### Before (Deprecated MCP API)
```typescript
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider()
+ provider: new AnthropicProvider(),
});
-const server = await composio.mcp.create(
- "server-name",
+const server = await composio.deprecated.mcp.create(
+ 'server-name',
[
{
- toolkit: "gmail",
- authConfigId: "ac_config",
- allowedTools: ["GMAIL_FETCH_EMAILS"]
- }
+ authConfigId: 'ac_config',
+ allowedTools: ['GMAIL_FETCH_EMAILS'],
+ },
],
{ isChatAuth: true }
);
const urls = await server.getServer({
- userId: "user123"
+ userId: 'user123',
});
```
-### After (Experimental MCP)
+### After (Current MCP API)
```typescript
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider(),
});
-const mcpConfig = await composio.experimental.mcpConfig.create(
- "server-name",
- [
- {
- authConfigId: "ac_config",
- allowedTools: ["GMAIL_FETCH_EMAILS"]
- }
- ],
- { isChatAuth: true }
-);
+const mcpConfig = await composio.mcp.create('server-name', {
+ toolkits: [{ toolkit: 'gmail', authConfigId: 'ac_config' }],
+ allowedTools: ['GMAIL_FETCH_EMAILS'],
+ manuallyManageConnections: true, // Equivalent to isChatAuth: true
+});
-const servers = await composio.experimental.mcp.getServer(
- "user123",
- mcpConfig.id
-);
+const serverInstance = await composio.mcp.generate('user123', mcpConfig.id);
```
+### Key Differences
+
+1. **API Location**: Moved from `composio.deprecated.mcp` to `composio.mcp`
+2. **Configuration Structure**: Simplified toolkit configuration with flexible options
+3. **Response Format**: Returns `MCPServerInstance` instead of provider-specific formats
+4. **Method Names**: `generate()` instead of `getServer()`
+5. **Authentication**: `manuallyManageConnections` instead of `isChatAuth`
+
## Troubleshooting
### Common Issues
-1. **Provider mismatch**: Ensure your provider supports the experimental MCP features
-2. **Auth config not found**: Verify your auth configuration IDs are correct
-3. **Tool not available**: Check that tools are properly configured in your auth config
-4. **Connection timeout**: MCP clients need to remain active while tools are being used
+1. **Auth config not found**: Verify your auth configuration IDs are correct and exist
+ ```typescript
+ // Verify auth config exists
+ try {
+ const authConfig = await composio.authConfigs.get('ac_your_config_id');
+ console.log('Auth config found:', authConfig.toolkit);
+ } catch (error) {
+ console.error('Auth config not found:', error.message);
+ }
+ ```
+
+2. **Tool not available**: Check that tools are properly configured in your toolkit
+ ```typescript
+ // List available tools for a toolkit
+ const tools = await composio.tools.list({ toolkit: 'gmail' });
+ console.log('Available Gmail tools:', tools.map(t => t.slug));
+ ```
+
+3. **Connection timeout**: MCP clients need to remain active while tools are being used
+ ```typescript
+ // Set appropriate timeouts for long-running operations
+ const transport = new SSEClientTransport(new URL(serverInstance.url), {
+ timeout: 30000 // 30 seconds
+ });
+ ```
+
+4. **Server instance not found**: Ensure the MCP configuration ID is valid
+ ```typescript
+ // Verify configuration exists before generating instance
+ try {
+ const config = await composio.mcp.get(mcpConfigId);
+ const instance = await composio.mcp.generate(userId, mcpConfigId);
+ } catch (error) {
+ console.error('Configuration not found:', error.message);
+ }
+ ```
+
+5. **Validation errors**: Check that your configuration parameters are correct
+ ```typescript
+ // Ensure toolkits array is properly formatted
+ const mcpConfig = await composio.mcp.create('server-name', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'ac_valid_id' }, // Valid format
+ 'github', // Also valid for default auth
+ ],
+ allowedTools: ['GMAIL_FETCH_EMAILS'], // Must be valid tool slugs
+ manuallyManageConnections: false, // Must be boolean
+ });
+ ```
### Debug Mode
Enable debug logging to troubleshoot issues:
```typescript
+// Set environment variable for debug logging
+process.env.COMPOSIO_LOG_LEVEL = 'debug';
+
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider(),
- // Additional debug configuration if available
+});
+
+// Additional debugging
+console.log('Composio config:', {
+ baseURL: composio.config?.baseURL,
+ hasApiKey: !!composio.config?.apiKey,
});
```
-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.
+### Getting Help
+
+If you encounter issues:
+
+1. Check the [Composio documentation](https://docs.composio.dev)
+2. Review your auth configurations and connected accounts
+3. Verify that your MCP client is compatible with the Server-Sent Events transport
+4. Ensure your API key has the necessary permissions
+
+## Conclusion
+
+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:
+
+- **Comprehensive management**: Full CRUD operations for MCP server configurations
+- **User isolation**: Generate unique server instances for individual users
+- **Flexible authentication**: Choose between Composio-managed or manual account management
+- **Universal compatibility**: Works with any MCP-compatible client
+
+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.
diff --git a/ts/docs/api/mcp.md b/ts/docs/api/mcp.md
index d481c08e3..720acb220 100644
--- a/ts/docs/api/mcp.md
+++ b/ts/docs/api/mcp.md
@@ -1,429 +1,413 @@
+# MCP API
-# MCP (Model Control Protocol) API
-
-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.
+The MCP (Model Control Protocol) API provides advanced server management capabilities for creating, configuring, and managing MCP servers with enhanced features.
## Overview
-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:
-
-- Create MCP servers that expose specific toolkits and tools
-- Manage authentication for MCP servers
-- Generate secure URLs for AI agents to connect to MCP servers
-- Support multiple AI frameworks through provider-specific transformations
-
-## Methods
+The MCP class offers comprehensive CRUD operations for MCP servers, including:
-### create(name, toolkitConfigs, authOptions?)
+- Creating custom MCP configurations with toolkit-specific settings
+- Listing and filtering servers with pagination
+- Retrieving detailed server information
+- Updating server configurations
+- Deleting servers
+- Managing server instances for users
-Creates a new MCP server with specified toolkit configurations.
+## Getting Started
```typescript
-// Create an MCP server with Gmail toolkit
-const server = await composio.mcp.create(
- "my-gmail-server",
- [
- {
- toolkit: "gmail",
- authConfigId: "ac_sdhkjfhjksdk",
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
- }
- ],
- { isChatAuth: true }
-);
+import { Composio } from '@composio/core';
-// Create an MCP server with multiple toolkits
-const multiToolServer = await composio.mcp.create(
- "multi-tool-server",
- [
+const composio = new Composio();
+const userId = "xxx-oooo-xxx";
+
+// create an MCP Server Config
+const server = await composio.mcp.create('my-mcp-server', {
+ toolkits: [
{
- toolkit: "github",
- authConfigId: "ac_github123",
- allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_REPO"]
+ toolkit: 'slack',
+ authConfigId: 'ac_12324343',
+ allowedTools: ['SLACK_SEND_MESSAGE'],
},
- {
- toolkit: "slack",
- authConfigId: "ac_slack456",
- allowedTools: ["SLACK_SEND_MESSAGE"]
- }
- ]
-);
-
-// Use the convenience method to get server URLs
-const urls = await server.getServer({
- connectedAccountIds: { gmail: "connected_account_id" }
+ ],
});
+
+// get an instance for a user
+const mcp = await server.generate(userId);
+
+// using the global api
+const mcp = await composio.mcp.generate(userId, server.id);
+
+/** mcp
+ * {
+ * ...
+ * id: "serverid",
+ * url: "mcp-server.com/mcp",
+ * ...
+ * }
+ * /
+
+// use the mcp with your mcp-client
```
-**Parameters:**
+## Methods
-- `name` (string): Unique name for the MCP server
-- `toolkitConfigs` (MCPToolkitConfig[]): Array of toolkit configurations
- - `toolkit`: The toolkit slug (e.g., "gmail", "github")
- - `authConfigId`: The auth configuration ID to use
- - `allowedTools`: Array of specific tool IDs to expose
-- `authOptions` (MCPAuthOptions): Optional authentication options
- - `isChatAuth`: Whether to use Composio-managed authentication
+### create(name, config)
-**Returns:** Promise<McpServerCreateResponse> - Created server details with convenience `getServer` method
+Creates a new MCP server configuration with specified toolkits and authentication settings.
-**Throws:** ValidationError if configurations are invalid or server creation fails
+**Parameters:**
-### getServer(id, params, authOptions?)
+- `name` (string): Unique name for the MCP configuration
+- `config` (MCPConfigCreationParams): Configuration object containing:
+ - `toolkits` (Array): Array of toolkit configurations
+ - `toolkit` (string, optional): Toolkit identifier (e.g., "github", "slack")
+ - `authConfigId` (string, optional): Auth configuration ID
+ - `allowedTools` (string[], optional): Specific tools to enable
+ - `manuallyManageConnections` (boolean, optional): Whether to manually manage account connections (default: false)
-Retrieves server URLs for an existing MCP server. This method generates secure URLs that AI agents can use to connect to the MCP server.
+**Returns:** `Promise<MCPConfigCreateResponse>`
-```typescript
-// Get URLs for a server using connected account IDs
-const urls = await composio.mcp.getServer("server-uuid", {
- connectedAccountIds: {
- gmail: "connected_account_123",
- github: "connected_account_456"
- }
-});
+**Example:**
-// Get URLs for a server using user ID
-const userUrls = await composio.mcp.getServer("server-uuid", {
- userId: "user_123"
+```typescript
+const server = await composio.mcp.create('personal-mcp-server', {
+ toolkits: [
+ {
+ toolkit: 'github',
+ authConfigId: 'ac_xyz',
+ allowedTools: ['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS'],
+ },
+ {
+ toolkit: 'slack',
+ authConfigId: 'ac_abc',
+ allowedTools: ['SLACK_SEND_MESSAGE'],
+ },
+ ],
+ manuallyManageConnections: false,
});
-// Override authentication options
-const customAuthUrls = await composio.mcp.getServer(
- "server-uuid",
- { userId: "user_123" },
- { isChatAuth: false }
-);
+// Get server instance for a user
+const mcp = await server.generate('user_12345');
```
-**Parameters:**
+### list(options)
-- `id` (string): Server UUID
-- `params` (MCPGetServerParams): Parameters for getting server URLs
- - Either `connectedAccountIds` (object mapping toolkit names to account IDs) OR `userId` (string)
-- `authOptions` (MCPAuthOptions): Optional authentication options to override server defaults
+Lists MCP servers with optional filtering and pagination.
-**Returns:** Promise<T> - Transformed server URLs in provider-specific format
+**Parameters:**
-**Throws:** ValidationError if parameters are invalid or URL generation fails
+- `options` (MCPListParams): Filtering and pagination options
+ - `page` (number, optional): Page number for pagination (default: 1)
+ - `limit` (number, optional): Maximum items per page (default: 10)
+ - `toolkits` (string[], optional): Filter by toolkit names
+ - `authConfigs` (string[], optional): Filter by auth configuration IDs
+ - `name` (string, optional): Filter by server name (partial match)
-### list(options)
+**Returns:** `Promise<MCPListResponse>`
-Lists MCP server configurations with filtering options.
+**Example:**
```typescript
-// List all servers with pagination
-const servers = await composio.mcp.list({
- page: 1,
- limit: 10
+// List all servers
+const allServers = await composio.mcp.list({});
+
+// Paginated listing
+const pagedServers = await composio.mcp.list({
+ page: 2,
+ limit: 5,
});
-// List servers for specific toolkits
-const gmailServers = await composio.mcp.list({
- toolkits: ['gmail', 'google-calendar'],
- limit: 20
+// Filter by toolkit
+const githubServers = await composio.mcp.list({
+ toolkits: ['github', 'slack'],
});
-// List servers by auth config
-const authFilteredServers = await composio.mcp.list({
- authConfigs: ['auth_123', 'auth_456'],
- name: 'production'
+// Filter by name
+const personalServers = await composio.mcp.list({
+ name: 'personal',
});
```
-**Parameters:**
+### get(serverId)
-- `options` (object): Filtering and pagination options
- - `page`: Page number for pagination (default: 1)
- - `limit`: Number of items per page (default: 10)
- - `toolkits`: Filter by toolkit names
- - `authConfigs`: Filter by auth config IDs
- - `name`: Filter by server name
+Retrieves detailed information about a specific MCP server/config.
-**Returns:** Promise<McpListResponse> - List of MCP servers
+**Parameters:**
+
+- `serverId` (string): The unique identifier of the MCP server/config
-### get(id)
+**Returns:** `Promise<MCPItem>`
-Retrieves details of a specific MCP server.
+**Example:**
```typescript
-const serverDetails = await composio.mcp.get('server-uuid');
-console.log(serverDetails.name);
-console.log(serverDetails.toolkits);
-console.log(serverDetails.status);
+const server = await composio.mcp.get('mcp_12345');
+
+console.log(server.name); // "My Personal MCP Server"
+console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
+console.log(server.toolkits); // ["github", "slack"]
+console.log(server.serverInstanceCount); // 3
+
+// Access setup commands for different clients
+console.log(server.commands.claude); // Claude setup command
+console.log(server.commands.cursor); // Cursor setup command
+console.log(server.commands.windsurf); // Windsurf setup command
```
-**Parameters:**
+### update(serverId, config)
-- `id` (string): Server UUID
+Updates an existing MCP server configuration.
+
+**Parameters:**
-**Returns:** Promise<McpRetrieveResponse> - Server details including configuration and metadata
+- `serverId` (string): The unique identifier of the MCP server to update
+- `config` (MCPUpdateParams): Update configuration parameters
+ - `name` (string, optional): New server name
+ - `toolkits` (Array, optional): Updated toolkit configurations
+ - `manuallyManageConnections` (boolean, optional): Connection management setting
-### update(id, name, toolkitConfigs, authOptions?)
+**Returns:** `Promise<MCPItem>`
-Updates an MCP server configuration.
+**Example:**
```typescript
-const updatedServer = await composio.mcp.update(
- "server-uuid",
- "updated-server-name",
- [
+// Update server name only
+const updatedServer = await composio.mcp.update('mcp_12345', {
+ name: 'My Updated MCP Server',
+});
+
+// Update toolkits and tools
+const serverWithNewTools = await composio.mcp.update('mcp_12345', {
+ toolkits: [
+ {
+ toolkit: 'github',
+ authConfigId: 'auth_abc123',
+ allowedTools: ['GITHUB_CREATE_ISSUE', 'GITHUB_LIST_REPOS'],
+ },
{
- toolkit: "gmail",
- authConfigId: "ac_new_auth_config",
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL", "GMAIL_CREATE_DRAFT"]
- }
+ toolkit: 'slack',
+ authConfigId: 'auth_xyz789',
+ allowedTools: ['SLACK_SEND_MESSAGE', 'SLACK_LIST_CHANNELS'],
+ },
+ ],
+});
+
+// Complete update
+const fullyUpdatedServer = await composio.mcp.update('mcp_12345', {
+ name: 'Production MCP Server',
+ toolkits: [
+ {
+ toolkit: 'gmail',
+ authConfigId: 'auth_gmail_prod',
+ allowedTools: ['GMAIL_SEND_EMAIL', 'GMAIL_FETCH_EMAILS'],
+ },
],
- { isChatAtuh: true }
-);
+ manuallyManageConnections: false,
+});
```
-**Parameters:**
+### delete(serverId)
-- `id` (string): Server UUID
-- `name` (string): New name for the server
-- `toolkitConfigs` (MCPToolkitConfig[]): Updated toolkit configurations
-- `authOptions` (MCPAuthOptions): Updated authentication options
+Permanently deletes an MCP server configuration.
+
+**Parameters:**
-**Returns:** Promise<McpUpdateResponse> - Updated server details
+- `serverId` (string): The unique identifier of the MCP server to delete
-### delete(id)
+**Returns:** `Promise<{id: string; deleted: boolean}>`
-Deletes an MCP server.
+**Example:**
```typescript
-const result = await composio.mcp.delete('server-uuid');
-console.log(result.deleted); // true
+// Delete a server
+const result = await composio.mcp.delete('mcp_12345');
+
+if (result.deleted) {
+ console.log(`Server ${result.id} has been successfully deleted`);
+} else {
+ console.log(`Failed to delete server ${result.id}`);
+}
+
+// With error handling
+try {
+ const result = await composio.mcp.delete('mcp_12345');
+ console.log('Deletion successful:', result);
+} catch (error) {
+ console.error('Failed to delete MCP server:', error.message);
+}
+
+// Verify deletion
+await composio.mcp.delete('mcp_12345');
+const servers = await composio.mcp.list({});
+const serverExists = servers.items.some(server => server.id === 'mcp_12345');
+console.log('Server still exists:', serverExists); // Should be false
```
-**Parameters:**
+### generate(userId, mcpConfigId, options?)
+
+Creates a server instance for a specific user.
-- `id` (string): Server UUID
+**Parameters:**
-**Returns:** Promise<McpDeleteResponse> - Deletion confirmation
+- `userId` (string): External user ID from your database
+- `mcpConfigId` (string): MCP configuration ID
+- `options` (MCPGetInstanceParams, optional): Additional options
+ - `manuallyManageConnections` (boolean, optional): Whether to manually manage connections
-### generateUrl(params)
+**Returns:** `Promise<MCPServerInstance>`
-Generates URLs for MCP server access. This is a lower-level method primarily used internally.
+**Example:**
```typescript
-const urlResponse = await composio.mcp.generateUrl({
- userIds: ['user123'],
- connectedAccountIds: ['account456'],
- mcpServerId: 'server-uuid',
- managedAuthByComposio: true
+const mcp = await composio.mcp.generate('user_12345', 'mcp_67890', {
+ manuallyManageConnections: false,
});
+
+console.log(mcp.url); // Server URL for the user
+console.log(mcp.allowedTools); // Available tools
```
-**Parameters:**
+## Data Types
-- `params` (GenerateURLParams): URL generation parameters
- - `userIds`: Array of user IDs
- - `connectedAccountIds`: Array of connected account IDs
- - `mcpServerId`: MCP server ID
- - `managedAuthByComposio`: Whether to use Composio-managed auth
+### MCPItem
-**Returns:** Promise<GenerateURLResponse> - Generated URLs
+Complete MCP server information including:
-## Provider Integration
+- `id`: Unique server identifier
+- `name`: Human-readable server name
+- `allowedTools`: Array of enabled tool identifiers
+- `authConfigIds`: Array of auth configuration IDs
+- `toolkits`: Array of toolkit names
+- `commands`: Setup commands for different clients (Claude, Cursor, Windsurf)
+- `MCPUrl`: Server connection URL
+- `toolkitIcons`: Map of toolkit icons
+- `serverInstanceCount`: Number of active instances
-Different AI frameworks expect MCP server URLs in different formats. Composio automatically handles these transformations through provider-specific implementations.
+### MCPListResponse
-### Using with Providers
+Paginated list response containing:
-```typescript
-import { Composio } from '@composio/core';
-import { MastraProvider } from '@composio/mastra';
-import { AnthropicProvider } from '@composio/anthropic';
+- `items`: Array of MCPItem objects
+- `currentPage`: Current page number
+- `totalPages`: Total number of pages
-// With Mastra provider - returns key-value URL mapping
-const composioMastra = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
- provider: new MastraProvider()
-});
-
-const mastraServer = await composioMastra.mcp.create(...);
-const mastraUrls = await mastraServer.getServer({
- connectedAccountIds: { gmail: "account_id" }
-});
-// Returns: { "server-0": { url: "..." } }
+### MCPServerInstance
-// With Anthropic provider - returns array of server info
-const composioAnthropic = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider()
-});
+User-specific server instance containing:
-const anthropicServer = await composioAnthropic.mcp.create(...);
-const anthropicUrls = await anthropicServer.getServer({
- connectedAccountIds: { gmail: "account_id" }
-});
-// Returns: [{ url: URL, name: "...", toolkit: "gmail" }]
-```
+- `id`: Server identifier
+- `name`: Server name
+- `type`: Connection type (always 'streamable_http')
+- `url`: User-specific connection URL
+- `userId`: Associated user ID
+- `allowedTools`: Available tools for the user
+- `authConfigs`: Associated auth configurations
-### Supported Providers
+## Error Handling
-- **Anthropic** - Returns McpServerUrlInfo[]
-- **OpenAI** - Returns McpServerUrlInfo[]
-- **LangChain** - Returns McpServerUrlInfo[]
-- **Vercel** - Returns McpServerUrlInfo[]
-- **Google** - Returns McpServerUrlInfo[]
-- **CloudFlare** - Returns McpServerUrlInfo[]
-- **Mastra** - Returns custom key-value URL mapping
+All methods can throw the following exceptions:
-## Types
+- **ValidationError**: When input parameters are invalid or malformed
+- **Error**: When API operations fail (server not found, network issues, etc.)
-### MCPToolkitConfig
+### Example Error Handling
```typescript
-interface MCPToolkitConfig {
- toolkit: string; // Toolkit slug (e.g., "gmail", "github")
- authConfigId: string; // Auth configuration ID
- allowedTools: string[]; // Array of allowed tool IDs
+try {
+ const server = await composio.mcp.create('test-server', config);
+} catch (error) {
+ if (error instanceof ValidationError) {
+ console.error('Invalid configuration:', error.message);
+ } else {
+ console.error('API error:', error.message);
+ }
}
```
-### MCPAuthOptions
+## Best Practices
-```typescript
-interface MCPAuthOptions {
- isChatAuth?: boolean; // Use Composio-managed authentication
-}
-```
+### 1. Server Naming
-### MCPGetServerParams
+Use descriptive, unique names for your MCP servers:
```typescript
-interface MCPGetServerParams {
- userId?: string; // User ID (XOR with connectedAccountIds)
- connectedAccountIds?: Record<string, string>; // Toolkit to account ID mapping
-}
+// Good
+'production-github-slack-server';
+'dev-testing-environment';
+'user-personal-tools';
+
+// Avoid
+'server1';
+'test';
+'mcp';
```
-### McpServerCreateResponse
+### 2. Toolkit Configuration
+
+Be specific about allowed tools to maintain security:
```typescript
-interface McpServerCreateResponse<T> {
- id: string; // Server UUID
- name: string; // Server name
- createdAt?: string; // Creation timestamp
- updatedAt?: string; // Last update timestamp
- status?: string; // Server status
- toolkits: string[]; // List of enabled toolkits
- getServer: (params: MCPGetServerParams) => Promise<T>; // Convenience method
+// Specific tools (recommended)
+{
+ toolkit: "github",
+ allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
}
-```
-
-### McpListResponse
-```typescript
-interface McpListResponse {
- items?: Array<{
- id: string;
- name: string;
- createdAt?: string;
- updatedAt?: string;
- status?: string;
- }>;
+// Avoid allowing all tools unless necessary
+{
+ toolkit: "github"
+ // No allowedTools = all tools enabled
}
```
-### McpServerUrlInfo
+### 3. Connection Management
+
+Choose the appropriate connection management strategy:
```typescript
-interface McpServerUrlInfo {
- url: URL; // MCP server URL
- name: string; // Server instance name
- toolkit?: string; // Associated toolkit
+// For chat based agents
+{
+ manuallyManageConnections: false;
+}
+
+// For background agents, where you have to pre connect all the accounts
+{
+ manuallyManageConnections: true;
}
```
-## Complete Example
+### 4. Pagination
-Here's a complete example of using MCP with an AI agent:
+Use pagination for large server lists:
```typescript
-import { Composio } from '@composio/core';
-import { MastraProvider } from '@composio/mastra';
-import { MCPClient } from '@mastra/mcp';
-import { Agent } from '@mastra/core/agent';
-import { openai } from '@ai-sdk/openai';
-
-// Initialize Composio with Mastra provider
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
- provider: new MastraProvider(),
-});
+let page = 1;
+let allServers = [];
-// Create an MCP server with Gmail toolkit
-const mcpServer = await composio.mcp.create(
- "gmail-assistant",
- [
- {
- toolkit: "gmail",
- authConfigId: "ac_your_auth_config",
- allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
- }
- ],
- { isChatAuth: true }
-);
+while (true) {
+ const response = await composio.mcp.list({
+ page,
+ limit: 50,
+ });
-// Get server URLs for connected accounts
-const serverUrls = await mcpServer.getServer({
- connectedAccountIds: {
- "gmail": "your_connected_account_id"
- }
-});
-
-// Initialize MCP client with the server URLs
-const mcpClient = new MCPClient({
- servers: Object.fromEntries(
- Object.entries(serverUrls).map(([key, value]) => [
- key,
- { url: new URL(value.url) }
- ])
- )
-});
+ allServers.push(...response.items);
-// Get available tools from MCP
-const tools = await mcpClient.getTools();
-
-// Create an AI agent with MCP tools
-const gmailAgent = new Agent({
- name: 'Gmail Assistant',
- instructions: 'You are a helpful Gmail assistant.',
- model: openai('gpt-4'),
- tools,
-});
-
-// Use the agent
-const response = await gmailAgent.generate('Fetch my latest emails');
-console.log(response.text);
+ if (page >= response.totalPages) break;
+ page++;
+}
```
-## Best Practices
-
-1. **Toolkit Selection**: Only expose the tools that your AI agent needs to minimize the attack surface
-2. **Authentication**: Use Composio-managed authentication when possible for better security
-3. **Error Handling**: Always handle validation errors when creating or updating servers
-4. **Provider Choice**: Choose the appropriate provider based on your AI framework
-5. **Server Naming**: Use descriptive names that indicate the server's purpose
-6. **Tool Allowlisting**: Be specific about which tools to expose rather than exposing entire toolkits
+## Limitations
+- Toolkit updates replace the entire configuration (no merging)
+- Deleted servers cannot be recovered
+- Server instances are tied to specific user IDs
-## Error Handling
+## Support
-All MCP methods throw `ValidationError` when:
-- Input parameters fail Zod schema validation
-- API responses don't match expected schemas
-- Server operations fail (create, update, delete)
-- URL generation fails
+For issues with the MCP API:
-```typescript
-try {
- const server = await composio.mcp.create("my-server", toolkitConfigs);
-} catch (error) {
- if (error instanceof ValidationError) {
- console.error('Validation failed:', error.message);
- console.error('Cause:', error.cause);
- }
-}
-```
\ No newline at end of file
+1. Check the error message for validation issues
+2. Verify your server configurations are valid
+3. Ensure you have proper permissions for the requested operations
+4. Contact support with specific error details and reproduction steps
diff --git a/ts/docs/api/mcp.old.md b/ts/docs/api/mcp.old.md
new file mode 100644
index 000000000..d481c08e3
--- /dev/null
+++ b/ts/docs/api/mcp.old.md
@@ -0,0 +1,429 @@
+
+# MCP (Model Control Protocol) API
+
+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.
+
+## Overview
+
+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:
+
+- Create MCP servers that expose specific toolkits and tools
+- Manage authentication for MCP servers
+- Generate secure URLs for AI agents to connect to MCP servers
+- Support multiple AI frameworks through provider-specific transformations
+
+## Methods
+
+### create(name, toolkitConfigs, authOptions?)
+
+Creates a new MCP server with specified toolkit configurations.
+
+```typescript
+// Create an MCP server with Gmail toolkit
+const server = await composio.mcp.create(
+ "my-gmail-server",
+ [
+ {
+ toolkit: "gmail",
+ authConfigId: "ac_sdhkjfhjksdk",
+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
+ }
+ ],
+ { isChatAuth: true }
+);
+
+// Create an MCP server with multiple toolkits
+const multiToolServer = await composio.mcp.create(
+ "multi-tool-server",
+ [
+ {
+ toolkit: "github",
+ authConfigId: "ac_github123",
+ allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_GET_REPO"]
+ },
+ {
+ toolkit: "slack",
+ authConfigId: "ac_slack456",
+ allowedTools: ["SLACK_SEND_MESSAGE"]
+ }
+ ]
+);
+
+// Use the convenience method to get server URLs
+const urls = await server.getServer({
+ connectedAccountIds: { gmail: "connected_account_id" }
+});
+```
+
+**Parameters:**
+
+- `name` (string): Unique name for the MCP server
+- `toolkitConfigs` (MCPToolkitConfig[]): Array of toolkit configurations
+ - `toolkit`: The toolkit slug (e.g., "gmail", "github")
+ - `authConfigId`: The auth configuration ID to use
+ - `allowedTools`: Array of specific tool IDs to expose
+- `authOptions` (MCPAuthOptions): Optional authentication options
+ - `isChatAuth`: Whether to use Composio-managed authentication
+
+**Returns:** Promise<McpServerCreateResponse> - Created server details with convenience `getServer` method
+
+**Throws:** ValidationError if configurations are invalid or server creation fails
+
+### getServer(id, params, authOptions?)
+
+Retrieves server URLs for an existing MCP server. This method generates secure URLs that AI agents can use to connect to the MCP server.
+
+```typescript
+// Get URLs for a server using connected account IDs
+const urls = await composio.mcp.getServer("server-uuid", {
+ connectedAccountIds: {
+ gmail: "connected_account_123",
+ github: "connected_account_456"
+ }
+});
+
+// Get URLs for a server using user ID
+const userUrls = await composio.mcp.getServer("server-uuid", {
+ userId: "user_123"
+});
+
+// Override authentication options
+const customAuthUrls = await composio.mcp.getServer(
+ "server-uuid",
+ { userId: "user_123" },
+ { isChatAuth: false }
+);
+```
+
+**Parameters:**
+
+- `id` (string): Server UUID
+- `params` (MCPGetServerParams): Parameters for getting server URLs
+ - Either `connectedAccountIds` (object mapping toolkit names to account IDs) OR `userId` (string)
+- `authOptions` (MCPAuthOptions): Optional authentication options to override server defaults
+
+**Returns:** Promise<T> - Transformed server URLs in provider-specific format
+
+**Throws:** ValidationError if parameters are invalid or URL generation fails
+
+### list(options)
+
+Lists MCP server configurations with filtering options.
+
+```typescript
+// List all servers with pagination
+const servers = await composio.mcp.list({
+ page: 1,
+ limit: 10
+});
+
+// List servers for specific toolkits
+const gmailServers = await composio.mcp.list({
+ toolkits: ['gmail', 'google-calendar'],
+ limit: 20
+});
+
+// List servers by auth config
+const authFilteredServers = await composio.mcp.list({
+ authConfigs: ['auth_123', 'auth_456'],
+ name: 'production'
+});
+```
+
+**Parameters:**
+
+- `options` (object): Filtering and pagination options
+ - `page`: Page number for pagination (default: 1)
+ - `limit`: Number of items per page (default: 10)
+ - `toolkits`: Filter by toolkit names
+ - `authConfigs`: Filter by auth config IDs
+ - `name`: Filter by server name
+
+**Returns:** Promise<McpListResponse> - List of MCP servers
+
+### get(id)
+
+Retrieves details of a specific MCP server.
+
+```typescript
+const serverDetails = await composio.mcp.get('server-uuid');
+console.log(serverDetails.name);
+console.log(serverDetails.toolkits);
+console.log(serverDetails.status);
+```
+
+**Parameters:**
+
+- `id` (string): Server UUID
+
+**Returns:** Promise<McpRetrieveResponse> - Server details including configuration and metadata
+
+### update(id, name, toolkitConfigs, authOptions?)
+
+Updates an MCP server configuration.
+
+```typescript
+const updatedServer = await composio.mcp.update(
+ "server-uuid",
+ "updated-server-name",
+ [
+ {
+ toolkit: "gmail",
+ authConfigId: "ac_new_auth_config",
+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL", "GMAIL_CREATE_DRAFT"]
+ }
+ ],
+ { isChatAtuh: true }
+);
+```
+
+**Parameters:**
+
+- `id` (string): Server UUID
+- `name` (string): New name for the server
+- `toolkitConfigs` (MCPToolkitConfig[]): Updated toolkit configurations
+- `authOptions` (MCPAuthOptions): Updated authentication options
+
+**Returns:** Promise<McpUpdateResponse> - Updated server details
+
+### delete(id)
+
+Deletes an MCP server.
+
+```typescript
+const result = await composio.mcp.delete('server-uuid');
+console.log(result.deleted); // true
+```
+
+**Parameters:**
+
+- `id` (string): Server UUID
+
+**Returns:** Promise<McpDeleteResponse> - Deletion confirmation
+
+### generateUrl(params)
+
+Generates URLs for MCP server access. This is a lower-level method primarily used internally.
+
+```typescript
+const urlResponse = await composio.mcp.generateUrl({
+ userIds: ['user123'],
+ connectedAccountIds: ['account456'],
+ mcpServerId: 'server-uuid',
+ managedAuthByComposio: true
+});
+```
+
+**Parameters:**
+
+- `params` (GenerateURLParams): URL generation parameters
+ - `userIds`: Array of user IDs
+ - `connectedAccountIds`: Array of connected account IDs
+ - `mcpServerId`: MCP server ID
+ - `managedAuthByComposio`: Whether to use Composio-managed auth
+
+**Returns:** Promise<GenerateURLResponse> - Generated URLs
+
+## Provider Integration
+
+Different AI frameworks expect MCP server URLs in different formats. Composio automatically handles these transformations through provider-specific implementations.
+
+### Using with Providers
+
+```typescript
+import { Composio } from '@composio/core';
+import { MastraProvider } from '@composio/mastra';
+import { AnthropicProvider } from '@composio/anthropic';
+
+// With Mastra provider - returns key-value URL mapping
+const composioMastra = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new MastraProvider()
+});
+
+const mastraServer = await composioMastra.mcp.create(...);
+const mastraUrls = await mastraServer.getServer({
+ connectedAccountIds: { gmail: "account_id" }
+});
+// Returns: { "server-0": { url: "..." } }
+
+// With Anthropic provider - returns array of server info
+const composioAnthropic = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new AnthropicProvider()
+});
+
+const anthropicServer = await composioAnthropic.mcp.create(...);
+const anthropicUrls = await anthropicServer.getServer({
+ connectedAccountIds: { gmail: "account_id" }
+});
+// Returns: [{ url: URL, name: "...", toolkit: "gmail" }]
+```
+
+### Supported Providers
+
+- **Anthropic** - Returns McpServerUrlInfo[]
+- **OpenAI** - Returns McpServerUrlInfo[]
+- **LangChain** - Returns McpServerUrlInfo[]
+- **Vercel** - Returns McpServerUrlInfo[]
+- **Google** - Returns McpServerUrlInfo[]
+- **CloudFlare** - Returns McpServerUrlInfo[]
+- **Mastra** - Returns custom key-value URL mapping
+
+## Types
+
+### MCPToolkitConfig
+
+```typescript
+interface MCPToolkitConfig {
+ toolkit: string; // Toolkit slug (e.g., "gmail", "github")
+ authConfigId: string; // Auth configuration ID
+ allowedTools: string[]; // Array of allowed tool IDs
+}
+```
+
+### MCPAuthOptions
+
+```typescript
+interface MCPAuthOptions {
+ isChatAuth?: boolean; // Use Composio-managed authentication
+}
+```
+
+### MCPGetServerParams
+
+```typescript
+interface MCPGetServerParams {
+ userId?: string; // User ID (XOR with connectedAccountIds)
+ connectedAccountIds?: Record<string, string>; // Toolkit to account ID mapping
+}
+```
+
+### McpServerCreateResponse
+
+```typescript
+interface McpServerCreateResponse<T> {
+ id: string; // Server UUID
+ name: string; // Server name
+ createdAt?: string; // Creation timestamp
+ updatedAt?: string; // Last update timestamp
+ status?: string; // Server status
+ toolkits: string[]; // List of enabled toolkits
+ getServer: (params: MCPGetServerParams) => Promise<T>; // Convenience method
+}
+```
+
+### McpListResponse
+
+```typescript
+interface McpListResponse {
+ items?: Array<{
+ id: string;
+ name: string;
+ createdAt?: string;
+ updatedAt?: string;
+ status?: string;
+ }>;
+}
+```
+
+### McpServerUrlInfo
+
+```typescript
+interface McpServerUrlInfo {
+ url: URL; // MCP server URL
+ name: string; // Server instance name
+ toolkit?: string; // Associated toolkit
+}
+```
+
+## Complete Example
+
+Here's a complete example of using MCP with an AI agent:
+
+```typescript
+import { Composio } from '@composio/core';
+import { MastraProvider } from '@composio/mastra';
+import { MCPClient } from '@mastra/mcp';
+import { Agent } from '@mastra/core/agent';
+import { openai } from '@ai-sdk/openai';
+
+// Initialize Composio with Mastra provider
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new MastraProvider(),
+});
+
+// Create an MCP server with Gmail toolkit
+const mcpServer = await composio.mcp.create(
+ "gmail-assistant",
+ [
+ {
+ toolkit: "gmail",
+ authConfigId: "ac_your_auth_config",
+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
+ }
+ ],
+ { isChatAuth: true }
+);
+
+// Get server URLs for connected accounts
+const serverUrls = await mcpServer.getServer({
+ connectedAccountIds: {
+ "gmail": "your_connected_account_id"
+ }
+});
+
+// Initialize MCP client with the server URLs
+const mcpClient = new MCPClient({
+ servers: Object.fromEntries(
+ Object.entries(serverUrls).map(([key, value]) => [
+ key,
+ { url: new URL(value.url) }
+ ])
+ )
+});
+
+// Get available tools from MCP
+const tools = await mcpClient.getTools();
+
+// Create an AI agent with MCP tools
+const gmailAgent = new Agent({
+ name: 'Gmail Assistant',
+ instructions: 'You are a helpful Gmail assistant.',
+ model: openai('gpt-4'),
+ tools,
+});
+
+// Use the agent
+const response = await gmailAgent.generate('Fetch my latest emails');
+console.log(response.text);
+```
+
+## Best Practices
+
+1. **Toolkit Selection**: Only expose the tools that your AI agent needs to minimize the attack surface
+2. **Authentication**: Use Composio-managed authentication when possible for better security
+3. **Error Handling**: Always handle validation errors when creating or updating servers
+4. **Provider Choice**: Choose the appropriate provider based on your AI framework
+5. **Server Naming**: Use descriptive names that indicate the server's purpose
+6. **Tool Allowlisting**: Be specific about which tools to expose rather than exposing entire toolkits
+
+## Error Handling
+
+All MCP methods throw `ValidationError` when:
+- Input parameters fail Zod schema validation
+- API responses don't match expected schemas
+- Server operations fail (create, update, delete)
+- URL generation fails
+
+```typescript
+try {
+ const server = await composio.mcp.create("my-server", toolkitConfigs);
+} catch (error) {
+ if (error instanceof ValidationError) {
+ console.error('Validation failed:', error.message);
+ console.error('Cause:', error.cause);
+ }
+}
+```
\ No newline at end of file
diff --git a/ts/docs/api/tool-router.experimental.md b/ts/docs/api/tool-router.experimental.md
new file mode 100644
index 000000000..4439ad128
--- /dev/null
+++ b/ts/docs/api/tool-router.experimental.md
@@ -0,0 +1,508 @@
+# ToolRouter Experimental API
+
+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.
+
+## Overview
+
+The ToolRouter class enables you to:
+
+- Create isolated sessions with specific toolkit configurations
+- Manage authentication for multiple toolkits in a single session
+- Provide scoped MCP server access for testing and development
+- Route tool calls efficiently across different services
+
+## Getting Started
+
+```typescript
+import { Composio } from '@composio/core';
+
+const composio = new Composio();
+const userId = "xxx-ooo-xxx";
+
+// Access the experimental ToolRouter for specific toolkits
+const mcpSession = composio.experimental.toolRouter.createSession(userId, {
+ toolkits: ["github"]
+});
+
+// Access the experimental ToolRouter for specific auth configs
+const mcpSession = composio.experimental.toolRouter.createSession(userId, {
+ toolkits: [{
+ toolkit: "github",
+ authConfigId: "ac_xyz"
+ }]
+});
+
+```
+
+## Methods
+
+### createSession(userId, routerConfig)
+
+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.
+
+**Parameters:**
+
+- `userId` (string): Unique user identifier for the session owner
+- `routerConfig` (ToolRouterConfig): Configuration object containing:
+ - `toolkits` (Array): Array of toolkit configurations
+ - `toolkit` (string): Toolkit identifier (e.g., "gmail", "slack", "github")
+ - `authConfigId` (string, optional): Specific auth configuration ID for this toolkit
+ - `manuallyManageConnections` (boolean, optional): Whether to disable Composio's automatic account management tools (default: false)
+
+**Returns:** `Promise<ToolRouterSession>`
+
+**Example:**
+
+```typescript
+// Basic session with multiple toolkits
+const session = await composio.experimental.toolRouter.createSession('user_123456789', {
+ toolkits: ["gmail", "slack", "github", "hackernews"]
+});
+
+console.log('Session ID:', session.sessionId);
+console.log('MCP URL:', session.url);
+
+// Session with manual connection management and authConfigs
+const manualSession = await composio.experimental.toolRouter.createSession('user_789', {
+ toolkits: [
+ {
+ toolkit: 'slack',
+ authConfigId: 'ac_custom_slack',
+ },
+ ],
+ manuallyManageConnections: true,
+});
+
+// Use the session URL with your MCP client
+const mcpClient = new MCPClient(session.url);
+```
+
+## Data Types
+
+### ToolRouterConfig
+
+Configuration object for creating a tool router session:
+
+```typescript
+interface ToolRouterConfig {
+ toolkits?: string[] | ToolRouterToolkitConfig[];
+ manuallyManageConnections?: boolean; // Disables automatic account management tools
+}
+```
+
+### ToolRouterToolkitConfig
+
+Individual toolkit configuration within a router config:
+
+```typescript
+interface ToolRouterToolkitConfig {
+ toolkit: string; // Toolkit identifier
+ authConfigId?: string; // Optional auth configuration ID
+}
+```
+
+### ToolRouterSession
+
+Response object containing session details:
+
+```typescript
+interface ToolRouterSession {
+ sessionId: string; // Generated session identifier
+ url: string; // MCP server endpoint URL for this session
+}
+```
+
+## Usage Patterns
+
+### 1. Multi-Service Integration
+
+Create sessions that span multiple services for complex workflows:
+
+```typescript
+const integrationSession = await composio.experimental.toolRouter.createSession('user_456', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'ac_gmail_work' },
+ { toolkit: 'slack', authConfigId: 'ac_slack_team' },
+ { toolkit: 'github', authConfigId: 'ac_github_personal' },
+ { toolkit: 'notion', authConfigId: 'ac_notion_workspace' },
+ { toolkit: 'calendar', authConfigId: 'ac_gcal_primary' },
+ ],
+});
+
+// This session can now handle tools from all configured services
+```
+
+### 2. Development and Testing
+
+Create isolated environments for testing different tool combinations:
+
+```typescript
+const testSession = await composio.experimental.toolRouter.createSession('test_user', {
+ toolkits: ["hackernews", "weatherapi", "calculator"]
+});
+
+// Perfect for testing tool routing logic without auth complexity
+```
+
+### 3. User-Specific Sessions
+
+Create personalized sessions with user-specific auth configurations:
+
+```typescript
+async function createUserSession(userId: string, userPreferences: any) {
+ const userToolkits = [];
+
+ if (userPreferences.email) {
+ userToolkits.push({
+ toolkit: 'gmail',
+ authConfigId: `gmail_${userId}`,
+ });
+ }
+
+ if (userPreferences.messaging) {
+ userToolkits.push({
+ toolkit: 'slack',
+ authConfigId: `slack_${userId}`,
+ });
+ }
+
+ if (userPreferences.coding) {
+ userToolkits.push({
+ toolkit: 'github',
+ authConfigId: `github_${userId}`,
+ });
+ }
+
+ return await composio.experimental.toolRouter.createSession(userId, {
+ toolkits: userToolkits,
+ manuallyManageConnections: false,
+ });
+}
+```
+
+## Connection Management
+
+The `manuallyManageConnections` flag controls whether Composio automatically injects account management tools into your session.
+
+### Automatic Account Management (Default)
+
+When `manuallyManageConnections` is `false` or omitted, Composio injects helpful account management tools:
+
+1. Connection status checking tools - agents can verify if accounts are connected
+2. Connection URL generation tools - agents can prompt users to connect accounts
+3. Account linking helpers - streamlined authentication flows
+
+```typescript
+const autoSession = await composio.experimental.toolRouter.createSession('user_123', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'gmail_config' },
+ { toolkit: 'slack', authConfigId: 'slack_config' },
+ ],
+ // manuallyManageConnections defaults to false
+});
+```
+
+### Manual Connection Management
+
+When `manuallyManageConnections` is `true`, Composio disables automatic account management tools:
+
+```typescript
+const manualSession = await composio.experimental.toolRouter.createSession('user_123', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'gmail_config' },
+ { toolkit: 'slack', authConfigId: 'slack_config' },
+ ],
+ manuallyManageConnections: true,
+});
+
+// No account management tools are injected
+// You must manually ensure all required connections exist beforehand
+// Use the Composio SDK to pre-connect accounts:
+
+// Before creating the session, link accounts manually:
+const connectionRequest = await composio.connectedAccounts.link({
+ userId: 'user_123',
+ authConfigId: 'gmail_config',
+});
+// redirect user to the url to authenticate
+console.log(connectionRequest.redirectUrl);
+
+// wait for users to connect their account
+const connectedAccount = await connectionRequest.waitForConnection();
+
+// Now the session can use these pre-connected accounts
+// But agents cannot dynamically check status or prompt for new connections
+```
+
+### When to Use Each Approach
+
+**Use Automatic Account Management (`manuallyManageConnections: false`) when:**
+
+- Building interactive AI agents that can communicate with users
+- Creating chat-based applications where users can be prompted to connect accounts
+- Developing applications where connection status might change during runtime
+- You want agents to handle authentication flows dynamically
+
+**Use Manual Connection Management (`manuallyManageConnections: true`) when:**
+
+- Building automated background processes or workflows
+- Creating production systems where all connections are pre-configured
+- You need predictable behavior without user interaction
+- Security requirements mandate pre-approved connections only
+- Building server-side applications without user interface
+
+```typescript
+// Interactive AI Assistant - use automatic management
+const assistantSession = await toolRouter.createSession('user_456', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'user_gmail' },
+ { toolkit: 'calendar', authConfigId: 'user_calendar' },
+ ],
+ manuallyManageConnections: false, // Agent can prompt for connections
+});
+
+// Background Automation - use manual management
+const automationSession = await toolRouter.createSession('automation_service', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'service_gmail' },
+ { toolkit: 'sheets', authConfigId: 'service_sheets' },
+ ],
+ manuallyManageConnections: true, // Pre-configured connections only
+});
+```
+
+## Integration with MCP Clients
+
+The ToolRouter sessions are designed to work seamlessly with MCP (Model Control Protocol) clients:
+
+```typescript
+// Create a session
+const session = await composio.experimental.toolRouter.createSession('user_456', {
+ toolkits: [{ toolkit: 'gmail' }, { toolkit: 'slack' }, { toolkit: 'github' }],
+});
+
+// Use with Claude Desktop
+// Add to claude_desktop_config.json:
+/*
+{
+ "mcpServers": {
+ "composio-session": {
+ "command": "npx",
+ "args": ["@composio/core", "mcp"],
+ "env": {
+ "COMPOSIO_MCP_URL": session.url
+ }
+ }
+ }
+}
+*/
+
+// Use with custom MCP client
+import { MCPClient } from 'your-mcp-client';
+
+const mcpClient = new MCPClient({
+ serverUrl: session.url,
+ sessionId: session.sessionId,
+});
+
+await mcpClient.connect();
+
+// Now you can use tools from all configured toolkits
+const emails = await mcpClient.callTool('gmail_fetch_emails', { limit: 10 });
+const channels = await mcpClient.callTool('slack_list_channels', {});
+const repos = await mcpClient.callTool('github_list_repos', { user: 'username' });
+```
+
+## Error Handling
+
+Handle common errors when creating sessions:
+
+```typescript
+try {
+ const session = await composio.experimental.toolRouter.createSession(userId, config);
+ console.log('Session created successfully:', session.sessionId);
+} catch (error) {
+ if (error instanceof ValidationError) {
+ console.error('Invalid configuration:', error.message);
+ // Handle validation errors (malformed config, missing required fields)
+ } else if (error.message.includes('auth_config')) {
+ console.error('Authentication configuration error:', error.message);
+ // Handle auth config issues (invalid IDs, permissions)
+ } else if (error.message.includes('toolkit')) {
+ console.error('Toolkit configuration error:', error.message);
+ // Handle toolkit issues (unsupported toolkit, invalid name)
+ } else {
+ console.error('Unexpected error:', error.message);
+ // Handle other API errors
+ }
+}
+```
+
+## Best Practices
+
+### 1. Session Naming and Organization
+
+Use descriptive user IDs and maintain session records:
+
+```typescript
+// Good: Descriptive user identifiers
+const session = await toolRouter.createSession('user_john_doe_workspace_1', config);
+
+// Keep track of active sessions
+const activeSessions = new Map();
+activeSessions.set(userId, session);
+```
+
+### 2. Toolkit Selection
+
+Be intentional about which toolkits to include:
+
+```typescript
+// Good: Only include necessary toolkits
+const focusedSession = await toolRouter.createSession(userId, {
+ toolkits: [
+ { toolkit: 'gmail' }, // For email operations
+ { toolkit: 'calendar' }, // For scheduling
+ ],
+});
+
+// Avoid: Including unnecessary toolkits
+// This creates security risks and complexity
+```
+
+### 3. Auth Configuration Management
+
+Use specific auth configs for different contexts:
+
+```typescript
+// Production session
+const prodSession = await toolRouter.createSession(userId, {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'gmail_prod_config' },
+ { toolkit: 'slack', authConfigId: 'slack_prod_workspace' },
+ ],
+});
+
+// Development session
+const devSession = await toolRouter.createSession(userId, {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'gmail_dev_config' },
+ { toolkit: 'slack', authConfigId: 'slack_dev_workspace' },
+ ],
+});
+```
+
+### 4. Session Lifecycle Management
+
+Implement proper session cleanup:
+
+```typescript
+class SessionManager {
+ private sessions = new Map<string, ToolRouterSession>();
+
+ async createUserSession(userId: string, config: ToolRouterConfig) {
+ // Clean up existing session if any
+ if (this.sessions.has(userId)) {
+ await this.cleanupSession(userId);
+ }
+
+ const session = await toolRouter.createSession(userId, config);
+ this.sessions.set(userId, session);
+
+ // Set cleanup timer (optional)
+ setTimeout(() => this.cleanupSession(userId), 24 * 60 * 60 * 1000); // 24 hours
+
+ return session;
+ }
+
+ async cleanupSession(userId: string) {
+ // Implement session cleanup logic
+ this.sessions.delete(userId);
+ }
+}
+```
+
+## Use Cases
+
+### 1. AI Assistant Integration
+
+Create dynamic sessions for AI assistants that need access to multiple services:
+
+```typescript
+const assistantSession = await toolRouter.createSession('assistant_user_123', {
+ toolkits: [
+ { toolkit: 'gmail', authConfigId: 'user_email' },
+ { toolkit: 'calendar', authConfigId: 'user_calendar' },
+ { toolkit: 'slack', authConfigId: 'user_slack' },
+ { toolkit: 'github', authConfigId: 'user_github' },
+ ],
+});
+
+// AI can now help with email, scheduling, team communication, and code
+```
+
+### 2. Workflow Automation
+
+Set up sessions for automated workflows:
+
+```typescript
+const workflowSession = await toolRouter.createSession('workflow_engine', {
+ toolkits: [
+ { toolkit: 'gmail' },
+ { toolkit: 'slack' },
+ { toolkit: 'sheets' },
+ { toolkit: 'notion' },
+ ],
+ manuallyManageConnections: true, // Pre-configured connections
+});
+
+// Automated workflow can process emails, update spreadsheets, notify teams
+```
+
+### 3. Customer Support Tools
+
+Create specialized sessions for support agents:
+
+```typescript
+const supportSession = await toolRouter.createSession(`support_agent_${agentId}`, {
+ toolkits: [
+ { toolkit: 'zendesk', authConfigId: 'support_zendesk' },
+ { toolkit: 'slack', authConfigId: 'support_slack' },
+ { toolkit: 'gmail', authConfigId: 'support_email' },
+ { toolkit: 'sheets', authConfigId: 'support_tracking' },
+ ],
+});
+
+// Support agents can access tickets, communicate with team, send emails, track metrics
+```
+
+## Limitations and Considerations
+
+- **Session Isolation**: Each session is isolated and cannot directly communicate with other sessions
+- **Resource Limits**: There may be limits on the number of concurrent sessions per user
+- **Auth Config Requirements**: Some toolkits require specific auth configurations to function properly
+- **Session Persistence**: Sessions may have time limits and need to be refreshed periodically
+- **Toolkit Compatibility**: Not all toolkit combinations may work optimally together
+
+## Migration and Compatibility
+
+The ToolRouter experimental API is designed to complement existing Composio features:
+
+```typescript
+// Can be used alongside regular MCP servers
+const regularMCP = await composio.mcp.create('regular-server', serverConfig, options);
+const routerSession = await composio.experimental.toolRouter.createSession(userId, routerConfig);
+
+// Both can coexist and serve different purposes
+```
+
+## Support and Troubleshooting
+
+For issues with the ToolRouter Experimental API:
+
+1. **Validation Errors**: Check that all required fields are provided and toolkit names are correct
+2. **Auth Configuration Issues**: Verify that auth config IDs exist and have proper permissions
+3. **Connection Problems**: Ensure network connectivity and proper MCP client configuration
+4. **Toolkit Compatibility**: Some toolkits may have specific requirements or limitations
+
+For additional support, consult the Composio documentation or contact support with session details and error messages.
diff --git a/ts/examples/anthropic/src/experimental.mcp.ts b/ts/examples/anthropic/src/experimental.mcp.ts
index f6430db42..977328b3d 100644
--- a/ts/examples/anthropic/src/experimental.mcp.ts
+++ b/ts/examples/anthropic/src/experimental.mcp.ts
@@ -5,7 +5,7 @@ import Anthropic from '@anthropic-ai/sdk';
// 1. Initialize Composio.
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new AnthropicProvider({ cacheTools: true })
+ provider: new AnthropicProvider({ cacheTools: true }),
});
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
const allowedTools = ['GMAIL_FETCH_EMAILS'];
// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `${Date.now()}`,
- [
+const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
+ toolkits: [
{
+ toolkit: 'gmail',
authConfigId,
- allowedTools,
},
],
- { isChatAuth: true }
-);
+ allowedTools,
+ manuallyManageConnections: true,
+});
// 3. Retrieve the MCP server instance for the connected accounts
-const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
+const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
// 4. Initialize Anthropic client.
const anthropic = new Anthropic({
@@ -38,7 +36,13 @@ const anthropic = new Anthropic({
const stream = anthropic.beta.messages.stream({
model: 'claude-4-sonnet-20250514',
max_tokens: 64_000,
- mcp_servers: servers,
+ mcp_servers: [
+ {
+ name: mcp.name,
+ url: mcp.url,
+ type: 'url',
+ },
+ ],
messages: [
{
role: 'user',
diff --git a/ts/examples/google/src/experimental.mcp.ts b/ts/examples/google/src/experimental.mcp.ts
index dff802afc..44d758282 100644
--- a/ts/examples/google/src/experimental.mcp.ts
+++ b/ts/examples/google/src/experimental.mcp.ts
@@ -19,27 +19,24 @@ const externalUserId = '<externalUserId>'; // Replace it with the user id from y
const allowedTools = ['GMAIL_FETCH_EMAILS'];
// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `${Date.now()}`,
- [
+const mcpConfig = await composio.experimental.mcp.create(`${Date.now()}`, {
+ toolkits: [
{
- // https://platform.composio.dev/alberto_schiabel/2025-09-12/auth-configs/ac_ydsgH6ZRO1Xc
+ toolkit: 'gmail',
authConfigId,
allowedTools,
},
],
- { isChatAuth: true }
-);
+ manuallyManageConnections: true,
+});
// 3. Retrieve the MCP server instance for the user
-const url = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
+const server = await composio.experimental.mcp.generate(externalUserId, mcpConfig.id);
// 4. Create a generic MCP client.
// This client needs to remain "alive" not be dropped by the GC until
// the tools are retrieved from it.
-const serverParams = new SSEClientTransport(url);
+const serverParams = new SSEClientTransport(new URL(server.url));
const mcpClient = new MCPClient({
name: 'composio-mcp-client',
version: '1.0.0',
diff --git a/ts/examples/mastra/src/experimental.mcp.ts b/ts/examples/mastra/src/experimental.mcp.ts
index 7a8d055e5..2404d6b91 100644
--- a/ts/examples/mastra/src/experimental.mcp.ts
+++ b/ts/examples/mastra/src/experimental.mcp.ts
@@ -4,29 +4,10 @@ import { MastraProvider } from '@composio/mastra';
import { MCPClient as MastraMCPClient } from '@mastra/mcp';
import { Agent as MastraAgent } from '@mastra/core/agent';
-function wrapTools(servers: Record<string, any>, tools: Record<string, any>): Record<string, any> {
- const prefixes = Object.keys(servers);
-
- function removePrefix(str: string): string {
- for (const prefix of prefixes) {
- if (str.startsWith(prefix)) {
- return str.slice(prefix.length + 1);
- }
- }
- return str;
- }
-
- return Object.fromEntries(
- Object.entries(tools).map(([key, tool]) => {
- return [removePrefix(key), tool] as const;
- })
- );
-}
-
// 1. Initialize Composio.
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- provider: new MastraProvider()
+ provider: new MastraProvider(),
});
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
const allowedTools = ['GMAIL_FETCH_EMAILS'];
// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `${Date.now()}`,
- [
+const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
+ toolkits: [
{
- // https://platform.composio.dev/alberto_schiabel/2025-09-12/auth-configs/ac_uINV_uCV87lm
+ toolkit: 'gmail',
authConfigId,
- allowedTools,
},
],
- { isChatAuth: true }
-);
+ allowedTools,
+ manuallyManageConnections: true,
+});
// 3. Retrieve the MCP server instance for the user
-const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
+const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
// 4. Create a Mastra-specific MCP client.
// This client needs to remain "alive" not be dropped by the GC until
// the tools are retrieved from it.
const mcpClient = new MastraMCPClient({
- servers,
+ servers: {
+ composio: {
+ url: new URL(mcp.url),
+ },
+ },
});
// 5. Retrieve tools.
@@ -70,7 +52,7 @@ const agent = new MastraAgent({
Be concise and provide actionable information based on the email content.
`,
model: openai('gpt-4o-mini'),
- tools: wrapTools(servers, tools),
+ tools,
});
// Fetch and summarize recent emails.
diff --git a/ts/examples/mastra/src/experimental.tool-router.ts b/ts/examples/mastra/src/experimental.tool-router.ts
new file mode 100644
index 000000000..1412a0c0f
--- /dev/null
+++ b/ts/examples/mastra/src/experimental.tool-router.ts
@@ -0,0 +1,59 @@
+import { openai } from '@ai-sdk/openai';
+import { Composio } from '@composio/core';
+import { MastraProvider } from '@composio/mastra';
+import { MCPClient as MastraMCPClient } from '@mastra/mcp';
+import { Agent as MastraAgent } from '@mastra/core/agent';
+
+// 1. Initialize Composio.
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new MastraProvider(),
+});
+
+const externalUserId = '<external_user_id>'; // Replace it with the user id id
+
+// 2. Create an tool router session
+const mcpSession = await composio.experimental.toolRouter.createSession(externalUserId, {
+ toolkits: ["gmail"],
+ manuallyManageConnections: true,
+});
+
+
+// 3. Create a Mastra-specific MCP client.
+// This client needs to remain "alive" not be dropped by the GC until
+// the tools are retrieved from it.
+const mcpClient = new MastraMCPClient({
+ servers: {
+ composio: {
+ url: new URL(mcpSession.url),
+ },
+ },
+});
+
+// 4. Retrieve tools.
+const tools = await mcpClient.getTools();
+
+// 5. Pass tools to Mastra-specific Agent.
+const agent = new MastraAgent({
+ name: 'Gmail Assistant',
+ instructions: `
+ You are a helpful Gmail assistant that fetches and summarizes emails.
+ When fetching emails, provide a clear summary of the results including sender, subject, and date.
+ Be concise and provide actionable information based on the email content.
+ `,
+ model: openai('gpt-4o-mini'),
+ tools,
+});
+
+// Fetch and summarize recent emails.
+console.log('\n=== Fetching and Summarizing Recent Emails ===');
+const emailResponse = await agent.generate(
+ 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
+);
+console.log('\n📬 Email Summary:');
+console.log(emailResponse.text);
+
+console.log('\n✅ Gmail MCP Example completed successfully!');
+
+// 8. Close Mastra-specific MCP client.
+await mcpClient.disconnect();
diff --git a/ts/examples/mcp/.env.example b/ts/examples/mcp/.env.example
new file mode 100644
index 000000000..0e728257c
--- /dev/null
+++ b/ts/examples/mcp/.env.example
@@ -0,0 +1,6 @@
+# Composio API Key - Get it from https://app.composio.dev
+COMPOSIO_API_KEY=your_composio_api_key_here
+
+# Add other environment variables as needed for your example
+# OPENAI_API_KEY=your_openai_api_key_here
+# ANTHROPIC_API_KEY=your_anthropic_api_key_here
diff --git a/ts/examples/mcp/README.md b/ts/examples/mcp/README.md
new file mode 100644
index 000000000..9e58990c0
--- /dev/null
+++ b/ts/examples/mcp/README.md
@@ -0,0 +1,53 @@
+# Mcp Example
+
+This example demonstrates how to use Composio SDK for mcp.
+
+## Setup
+
+1. **Install dependencies:**
+ ```bash
+ pnpm install
+ ```
+
+2. **Configure environment:**
+ ```bash
+ cp .env.example .env
+ ```
+
+ Then edit `.env` and add your API keys:
+ - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
+
+## Running the Example
+
+```bash
+# Run the example
+pnpm start
+
+# Run in development mode (with file watching)
+pnpm dev
+```
+
+## What This Example Does
+
+- Initializes Composio SDK
+- Fetches available tools
+- Demonstrates basic usage patterns
+
+## Customization
+
+Edit `src/index.ts` to:
+- Add specific apps you want to integrate with
+- Implement your business logic
+- Add error handling and logging
+
+## Related Examples
+
+- [OpenAI Example](../openai) - Shows integration with OpenAI
+- [LangChain Example](../langchain) - Shows integration with LangChain
+- [More Examples](../) - Browse all available examples
+
+## Support
+
+- [Documentation](https://docs.composio.dev)
+- [Discord Community](https://discord.gg/composio)
+- [GitHub Issues](https://github.com/composio/composio/issues)
diff --git a/ts/examples/mcp/package.json b/ts/examples/mcp/package.json
new file mode 100644
index 000000000..c791a392f
--- /dev/null
+++ b/ts/examples/mcp/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "mcp-example",
+ "private": true,
+ "version": "0.1.0",
+ "description": "Example project for Mcp",
+ "main": "src/index.ts",
+ "scripts": {
+ "start": "bun src/index.ts",
+ "dev": "bun --watch src/index.ts",
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [
+ "composio",
+ "example",
+ "mcp"
+ ],
+ "author": "",
+ "license": "ISC",
+ "packageManager": "[email protected]",
+ "dependencies": {
+ "@ai-sdk/openai": "^2.0.35",
+ "@composio/core": "workspace:*",
+ "@composio/vercel": "workspace:*",
+ "@modelcontextprotocol/sdk": "^1.18.0",
+ "ai": "catalog:",
+ "dotenv": "^16.4.1"
+ },
+ "devDependencies": {
+ "@types/bun": "^1.2.9",
+ "typescript": "catalog:"
+ }
+}
diff --git a/ts/examples/mcp/src/index.ts b/ts/examples/mcp/src/index.ts
new file mode 100644
index 000000000..ac0d559a3
--- /dev/null
+++ b/ts/examples/mcp/src/index.ts
@@ -0,0 +1,62 @@
+import { openai } from '@ai-sdk/openai';
+import { Composio } from '@composio/core';
+import { VercelProvider } from '@composio/vercel';
+import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
+import { experimental_createMCPClient as createMCPClient, stepCountIs, streamText } from 'ai';
+import 'dotenv/config';
+
+// 1. Initialize Composio.
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new VercelProvider(),
+});
+
+const authConfigId = '<auth_config_id>'; // Use your auth config ID
+const externalUserId = '<extern_user_id>'; // Replace it with the user id
+const allowedTools = ['GMAIL_FETCH_EMAILS'];
+
+// 2. Create an MCP config
+const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
+ toolkits: [
+ {
+ toolkit: 'gmail',
+ authConfigId,
+ },
+ ],
+ allowedTools,
+ manuallyManageConnections: false,
+});
+
+// 3. Retrieve the MCP server instance for the user
+const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
+
+const serverParams = new SSEClientTransport(new URL(server.url));
+
+const mcpClient = await createMCPClient({
+ name: 'composio-mcp-client',
+ transport: serverParams,
+});
+
+// 5. Retrieve tools.
+const tools = await mcpClient.tools();
+
+// 6. Pass tools to Vercel-specific Agent.
+const stream = streamText({
+ model: openai('gpt-4o-mini'),
+ messages: [
+ {
+ role: 'user',
+ content: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,
+ },
+ ],
+ stopWhen: stepCountIs(5),
+ tools,
+});
+
+// 7. Execute the Vercel AI-specific Agent.
+for await (const textPart of stream.textStream) {
+ process.stdout.write(textPart);
+}
+
+// 8. Close Vercel AI's MCP client.
+await mcpClient.close();
diff --git a/ts/examples/mcp/tsconfig.json b/ts/examples/mcp/tsconfig.json
new file mode 100644
index 000000000..f736a53ab
--- /dev/null
+++ b/ts/examples/mcp/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "es2022",
+ "module": "esnext",
+ "declaration": true,
+ "declarationDir": "./dist",
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "moduleResolution": "bundler",
+ "skipLibCheck": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src"]
+}
diff --git a/ts/examples/openai/package.json b/ts/examples/openai/package.json
index f60e71187..1da3456d7 100644
--- a/ts/examples/openai/package.json
+++ b/ts/examples/openai/package.json
@@ -23,7 +23,7 @@
"@composio/openai": "workspace:*",
"@composio/openai-agents": "workspace:*",
"@modelcontextprotocol/sdk": "^1.18.0",
- "@openai/agents": "^0.1.3",
+ "@openai/agents": "^0.1.4",
"dotenv": "^16.4.1",
"openai": "^5.16.0",
"zod": "catalog:",
diff --git a/ts/examples/openai/src/agents-api/experiment.mcp.ts b/ts/examples/openai/src/agents-api/experiment.mcp.ts
index 05423bb75..827ecdfea 100644
--- a/ts/examples/openai/src/agents-api/experiment.mcp.ts
+++ b/ts/examples/openai/src/agents-api/experiment.mcp.ts
@@ -1,55 +1,41 @@
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
-import { Agent as OpenAIAgent, run } from '@openai/agents';
+import { hostedMcpTool, Agent as OpenAIAgent, run } from '@openai/agents';
import type { HostedMCPTool } from '@openai/agents';
import 'dotenv/config';
-function sanitizeString(input: string): string {
- return input.replace(/[^a-zA-Z0-9_-]+/g, '-');
-}
-
-function wrapTools<T>(servers: Array<HostedMCPTool<T>>): Array<HostedMCPTool<T>> {
- return servers.map(server => {
- const { server_label, ...rest } = server.providerData ?? {};
- return {
- ...server,
- providerData: {
- ...rest,
- /**
- * 'server_label' must start with a letter and consist of only letters, digits, '-' and '_'
- */
- server_label: sanitizeString(server_label),
- },
- };
- });
-}
-
// 1. Initialize Composio.
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new OpenAIAgentsProvider(),
+ allowTracking: false,
});
const authConfigId = '<auth_config_id>'; // Use your auth config ID
+const toolkit = 'gmail'; // slug of the toolkit
const externalUserId = '<external_user_id>'; // Replace it with the userId from your database
const allowedTools = ['GMAIL_FETCH_EMAILS'];
// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `gmail-mcp-${Date.now()}`,
- [
- {
- authConfigId,
- allowedTools,
- },
- ],
- { isChatAuth: true }
-);
+const mcpConfig = await composio.mcp.create(externalUserId, {
+ toolkits: [{ toolkit, authConfigId }],
+ allowedTools,
+});
// 3. Retrieve the MCP server instance for the connected accounts
-const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
+const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
+
+const tools: HostedMCPTool[] = [
+ hostedMcpTool({
+ serverLabel: server.name,
+ serverUrl: server.url,
+ requireApproval: {
+ never: {
+ toolNames: ['GMAIL_FETCH_EMAILS'],
+ },
+ },
+ }),
+];
// 4. Pass tools to OpenAI-specific Agent.
const agent = new OpenAIAgent({
@@ -60,7 +46,7 @@ const agent = new OpenAIAgent({
Be concise and provide actionable information based on the email content.
`,
model: 'gpt-4o-mini',
- tools: wrapTools(servers),
+ tools: tools,
});
// 5. Execute the OpenAI-specific agent.
diff --git a/ts/examples/openai/src/agents-api/experiment.tool-router.ts b/ts/examples/openai/src/agents-api/experiment.tool-router.ts
new file mode 100644
index 000000000..5babc3948
--- /dev/null
+++ b/ts/examples/openai/src/agents-api/experiment.tool-router.ts
@@ -0,0 +1,59 @@
+import { Composio } from '@composio/core';
+import { OpenAIAgentsProvider } from '@composio/openai-agents';
+import { hostedMcpTool, Agent as OpenAIAgent, run } from '@openai/agents';
+import type { HostedMCPTool } from '@openai/agents';
+import 'dotenv/config';
+
+// 1. Initialize Composio.
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new OpenAIAgentsProvider(),
+ allowTracking: false,
+});
+
+const externalUserId = 'default';
+
+// 2. Create an tool router session
+const mcpSession = await composio.experimental.toolRouter.createSession(externalUserId, {
+ toolkits: ["gmail", "github"],
+});
+
+// 3. Retrieve the MCP server instance for the tool router
+
+const tools: HostedMCPTool[] = [
+ hostedMcpTool({
+ serverLabel: 'composio tool router',
+ serverUrl: mcpSession.url,
+ requireApproval: {
+ never: {
+ toolNames: ['GMAIL_FETCH_EMAILS'],
+ },
+ },
+ }),
+];
+
+// 4. Pass tools to OpenAI-specific Agent.
+const agent = new OpenAIAgent({
+ name: 'Gmail Assistant',
+ instructions: `
+ You are a helpful Gmail assistant that fetches and summarizes emails.
+ When fetching emails, provide a clear summary of the results including sender, subject, and date.
+ Be concise and provide actionable information based on the email content.
+ `,
+ model: 'gpt-4o-mini',
+ tools: tools,
+});
+
+// 5. Execute the OpenAI-specific agent.
+// Fetch and summarize recent emails
+console.log('\n=== Fetching and Summarizing Recent Emails ===');
+const emailResponse = await run(
+ agent,
+ 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
+);
+console.log('\n📬 Email Summary:');
+
+const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);
+
+// @ts-ignore
+console.log(output?.content[0].text);
diff --git a/ts/examples/openai/src/experiment.mcp.ts b/ts/examples/openai/src/experiment.mcp.ts
deleted file mode 100644
index 94869d2b7..000000000
--- a/ts/examples/openai/src/experiment.mcp.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { Composio } from '@composio/core';
-import OpenAI from 'openai';
-import { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';
-import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
-import 'dotenv/config';
-
-function sanitizeString(input: string): string {
- return input.replace(/[^a-zA-Z0-9_-]+/g, '-');
-}
-
-async function wrapTools(client: MCPClient): Promise<Array<OpenAI.ChatCompletionFunctionTool>> {
- async function* listAllTools(client: MCPClient, maxTools = 128) {
- let cursor: string | undefined = undefined;
- let numTools = 0;
- while (numTools < maxTools) {
- const t = await client.listTools({cursor});
- for (const tool of t.tools) {
- yield tool;
- numTools++;
- }
- if (!t.nextCursor) {
- break;
- }
- cursor = t.nextCursor;
- }
- }
-
- const tools = await Array.fromAsync(listAllTools(client));
-
- return tools.map(tool => {
- return {
- type: 'function',
- function: {
- name: sanitizeString(tool.name),
- description: tool.description!,
- parameters: tool.inputSchema,
- strict: false,
- }
- }
- })
-}
-
-// 1. Initialize Composio.
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
-});
-
-const authConfigId = '<auth_config_id>'; // Use your auth config ID
-const externalUserId = '<external_user_id>'; // Replace it with the user id
-const allowedTools = ['GMAIL_FETCH_EMAILS'];
-
-// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `gmail-mcp-${Date.now()}`,
- [
- {
- authConfigId,
- allowedTools,
- },
- ],
- { isChatAuth: true }
-);
-
-// 3. Retrieve the MCP server instance for the connected accounts
-const url = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
-
-// 4. Create a generic MCP client.
-// This client needs to remain "alive" not be dropped by the GC until
-// the tools are retrieved from it.
-const serverParams = new SSEClientTransport(url);
-const mcpClient = new MCPClient({
- name: 'composio-mcp-client',
- version: '1.0.0',
-});
-
-// 5. Retrieve tools.
-await mcpClient.connect(serverParams);
-const tools = await wrapTools(mcpClient);
-console.dir(tools, { depth: null });
-console.log(`✅ Tools available: ${tools.map(t => t.function.name).join(', ')}\n`);
-
-// 6. Pass tools to OpenAI-specific Agent.
-const openai = new OpenAI();
-const response = await openai.chat.completions.create({
- model: 'gpt-4o-mini',
- messages: [
- {
- role: 'system',
- content: `
- You are a helpful Gmail assistant that fetches and summarizes emails.
- When fetching emails, provide a clear summary of the results including sender, subject, and date.
- Be concise and provide actionable information based on the email content.
- `,
- },
- {
- role: 'user',
- content: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,
- }
- ],
- tools,
- tool_choice: 'auto',
-});
-
-/**
- * If the assistant has tool calls, execute them and log the result
- */
-if (
- response.choices[0].message.tool_calls &&
- response.choices[0].message.tool_calls[0].type === 'function'
-) {
- console.log(JSON.stringify(response, null, 2));
- const toolCall = response.choices[0].message.tool_calls[0];
- if (toolCall.type === 'function') {
- console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);
- }
- const result = await composio.provider.handleToolCalls('default', response);
- console.log(result);
-}
-
-await mcpClient.close();
-
-console.log('\n✅ OpenAI MCP Example completed successfully!');
diff --git a/ts/examples/openai/src/responses-api/experiment.mcp.ts b/ts/examples/openai/src/responses-api/experiment.mcp.ts
index 18d9cc463..a4ca8307b 100644
--- a/ts/examples/openai/src/responses-api/experiment.mcp.ts
+++ b/ts/examples/openai/src/responses-api/experiment.mcp.ts
@@ -3,27 +3,11 @@ import { OpenAIResponsesProvider } from '@composio/openai';
import OpenAI from 'openai';
import 'dotenv/config';
-function sanitizeString(input: string): string {
- return input.replace(/[^a-zA-Z0-9_-]+/g, '-');
-}
-
-function wrapTools(servers: Array<OpenAI.Responses.Tool.Mcp>): Array<OpenAI.Responses.Tool.Mcp> {
- return servers.map(server => {
- const { server_label, ...rest } = server;
- return {
- ...rest,
- /**
- * 'server_label' must start with a letter and consist of only letters, digits, '-' and '_'
- */
- server_label: sanitizeString(server_label),
- };
- });
-}
-
// 1. Initialize Composio.
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new OpenAIResponsesProvider(),
+ allowTracking: false,
});
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
const allowedTools = ['GMAIL_FETCH_EMAILS'];
// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `gmail-mcp-${Date.now()}`,
- [
+const mcpConfig = await composio.mcp.create(`gmail-mcp-${Date.now()}`, {
+ toolkits: [
{
+ toolkit: 'gmail',
authConfigId,
- allowedTools,
},
],
- { isChatAuth: true }
-);
+ allowedTools,
+ manuallyManageConnections: true,
+});
// 3. Retrieve the MCP server instance for the connected accounts
-const servers = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
+const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
+
+const tools = [
+ {
+ type: 'mcp' as const,
+ server_label: mcp.name,
+ server_url: mcp.url,
+ },
+];
+console.log({ tools });
// 4. Pass tools to OpenAI-specific Agent.
const openai = new OpenAI();
@@ -57,9 +48,14 @@ const emailResponse = await openai.responses.create({
Be concise and provide actionable information based on the email content.
`,
input: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,
- tools: wrapTools(servers),
+ tools: tools,
});
+console.log(JSON.stringify(emailResponse, null, 2));
+
+const result = await composio.provider.handleToolCalls('default', emailResponse.output);
+console.log({ result });
+
const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);
console.log(
diff --git a/ts/examples/vercel/src/experimental.mcp.ts b/ts/examples/vercel/src/experimental.mcp.ts
index 21a952925..ac0d559a3 100644
--- a/ts/examples/vercel/src/experimental.mcp.ts
+++ b/ts/examples/vercel/src/experimental.mcp.ts
@@ -16,24 +16,21 @@ const externalUserId = '<extern_user_id>'; // Replace it with the user id
const allowedTools = ['GMAIL_FETCH_EMAILS'];
// 2. Create an MCP config
-const mcpConfig = await composio.experimental.mcpConfig.create(
- `${Date.now()}`,
- [
+const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
+ toolkits: [
{
- // https://platform.composio.dev/alberto_schiabel/2025-09-12/auth-configs/ac_ydsgH6ZRO1Xc
+ toolkit: 'gmail',
authConfigId,
- allowedTools,
},
],
- { isChatAuth: true }
-);
+ allowedTools,
+ manuallyManageConnections: false,
+});
// 3. Retrieve the MCP server instance for the user
-const url = await composio.experimental.mcp.getServer(externalUserId, mcpConfig.id, {
- limitTools: allowedTools,
-});
+const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
-const serverParams = new SSEClientTransport(url);
+const serverParams = new SSEClientTransport(new URL(server.url));
const mcpClient = await createMCPClient({
name: 'composio-mcp-client',
diff --git a/ts/examples/vercel/src/experimental.tool-router.ts b/ts/examples/vercel/src/experimental.tool-router.ts
new file mode 100644
index 000000000..4511adb1f
--- /dev/null
+++ b/ts/examples/vercel/src/experimental.tool-router.ts
@@ -0,0 +1,59 @@
+import { openai } from '@ai-sdk/openai';
+import { Composio } from '@composio/core';
+import { VercelProvider } from '@composio/vercel';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { experimental_createMCPClient as createMCPClient, stepCountIs, streamText } from 'ai';
+import 'dotenv/config';
+
+// 1. Initialize Composio.
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new VercelProvider(),
+});
+
+// 2. Create an MCP session
+console.log('🔄 Creating toolrouter session...');
+const mcp = await composio.experimental.toolRouter.createSession('default', {
+ toolkits: ['gmail', 'hackernews', 'github'],
+});
+
+console.log(JSON.stringify(mcp, null, 2));
+
+
+console.log(`✅ Toolrouter session created: ${mcp.sessionId}`);
+console.log(`🔄 Connecting to MCP Server: ${mcp.url}`);
+
+const serverParams = new StreamableHTTPClientTransport(new URL(mcp.url));
+
+const mcpClient = await createMCPClient({
+ name: 'composio-mcp-client',
+ transport: serverParams,
+});
+
+// 5. Retrieve tools.
+console.log(`🔄 Retrieving tools...`);
+const tools = await mcpClient.tools();
+console.log(`✅ Tools Retrieved`);
+Object.keys(tools).map(tool => console.log(` 📦 ${tool}`));
+
+// 6. Pass tools to Vercel-specific Agent.
+console.log(`🔄 Executing agent...`);
+const stream = streamText({
+ model: openai('gpt-4o-mini'),
+ messages: [
+ {
+ role: 'user',
+ content: `What's latest on hackernews?`,
+ },
+ ],
+ stopWhen: stepCountIs(5),
+ tools,
+});
+console.log(`🤖 Agent Response:`);
+// 7. Execute the Vercel AI-specific Agent.
+for await (const textPart of stream.textStream) {
+ process.stdout.write(textPart);
+}
+
+// 8. Close Vercel AI's MCP client.
+await mcpClient.close();
diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.ts
index c03a00dc6..bc89b69f9 100644
--- a/ts/packages/core/src/composio.ts
+++ b/ts/packages/core/src/composio.ts
@@ -5,7 +5,8 @@ import { Toolkits } from './models/Toolkits';
import { Triggers } from './models/Triggers';
import { AuthConfigs } from './models/AuthConfigs';
import { ConnectedAccounts } from './models/ConnectedAccounts';
-import { ExperimentalMCP, MCP } from './models/MCP';
+import { MCP } from './models/MCP.experimental';
+import { MCP as DeprecatedMCP } from './models/MCP';
import { telemetry } from './telemetry/Telemetry';
import { getSDKConfig, getToolkitVersionsFromEnv } from './utils/sdk';
import logger from './utils/logger';
@@ -17,15 +18,10 @@ import type { ComposioRequestHeaders } from './types/composio.types';
import { Files } from './models/Files';
import { getDefaultHeaders } from './utils/session';
import { ToolkitVersionParam } from './types/tool.types';
-import { MCPConfig } from './models/MCPConfig';
+import { ToolRouter } from './models/ToolRouter.experimental';
export type ComposioConfig<
- TProvider extends BaseComposioProvider<
- unknown,
- unknown,
- /* TMcpResponse */ unknown,
- /* TMcpExperimentalResponse */ unknown
- > = OpenAIProvider,
+ TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
> = {
/**
* The API key for the Composio API.
@@ -95,7 +91,7 @@ export type ComposioConfig<
* It is used to initialize the Composio SDK and provide a global configuration.
*/
export class Composio<
- TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown> = OpenAIProvider,
+ TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
> {
/**
* The Composio API client.
@@ -117,19 +113,22 @@ export class Composio<
triggers: Triggers;
provider: TProvider;
files: Files;
- // auth configs
authConfigs: AuthConfigs;
- // connected accounts
connectedAccounts: ConnectedAccounts;
-
- mcp: MCP<TProvider>;
+ mcp: MCP;
/**
* Experimental features
*/
experimental: {
- mcp: ExperimentalMCP<TProvider>;
- mcpConfig: MCPConfig<TProvider>;
+ toolRouter: ToolRouter;
+ };
+
+ /**
+ * Deprecated features
+ */
+ deprecated: {
+ mcp: DeprecatedMCP<TProvider>;
};
/**
@@ -204,7 +203,7 @@ export class Composio<
});
this.tools = new Tools(this.client, this.provider, this.config);
- this.mcp = new MCP(this.client, this.provider);
+ this.mcp = new MCP(this.client);
this.toolkits = new Toolkits(this.client);
this.triggers = new Triggers(this.client);
this.authConfigs = new AuthConfigs(this.client);
@@ -215,8 +214,23 @@ export class Composio<
* Initialize Experimental features
*/
this.experimental = {
- mcp: new ExperimentalMCP(this.client, this.provider),
- mcpConfig: new MCPConfig(this.mcp),
+ /**
+ * Experimental tool router
+ * Helps you create a single MCP server containing all the tools with smart routing.
+ *
+ * @description Allows you to create an isolated toolRouter MCP session for a user
+ */
+ toolRouter: new ToolRouter(this.client),
+ };
+
+ /**
+ * Initialize Deprecated features
+ */
+ this.deprecated = {
+ /**
+ * @deprecated this feature will be removed soon, use `composio.mcp`
+ */
+ mcp: new DeprecatedMCP(this.client, this.provider),
};
/**
diff --git a/ts/packages/core/src/models/MCP.experimental.ts b/ts/packages/core/src/models/MCP.experimental.ts
new file mode 100644
index 000000000..29ec36d0a
--- /dev/null
+++ b/ts/packages/core/src/models/MCP.experimental.ts
@@ -0,0 +1,430 @@
+import { Composio as ComposioClient } from '@composio/client';
+import { telemetry } from '../telemetry/Telemetry';
+import {
+ MCPConfigCreationParams,
+ MCPConfigCreationParamsSchema,
+ MCPConfigCreateResponse,
+ MCPConfigResponseSchema,
+ MCPServerInstance,
+ MCPGetInstanceParams,
+ MCPGetInstanceParamsSchema,
+ MCPListResponse,
+ MCPListParams,
+ MCPListParamsSchema,
+ MCPListResponseSchema,
+ MCPItemSchema,
+ MCPItem,
+ MCPUpdateParams,
+ MCPUpdateParamsSchema,
+} from '../types/mcp.experimental.types';
+import { MCPServerInstanceSchema } from '../types/mcp.experimental.types';
+import { ValidationError } from '../errors/ValidationErrors';
+import { transform } from '../utils/transform';
+import { McpUpdateResponse } from '@composio/client/resources.js';
+import { McpRetrieveResponse } from '@composio/client/resources';
+
+function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
+ return transform(response)
+ .with(MCPItemSchema)
+ .using(raw => ({
+ name: raw.name,
+ allowedTools: raw.allowed_tools,
+ id: raw.id,
+ authConfigIds: raw.auth_config_ids,
+ commands: raw.commands,
+ MCPUrl: raw.mcp_url,
+ toolkitIcons: raw.toolkit_icons,
+ serverInstanceCount: raw.server_instance_count,
+ toolkits: raw.toolkits,
+ }));
+}
+/**
+ * MCP (Model Control Protocol) class
+ * Handles MCP server operations.
+ * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
+ */
+export class MCP {
+ client: ComposioClient;
+
+ constructor(client: ComposioClient) {
+ this.client = client;
+ telemetry.instrument(this);
+ }
+
+ /**
+ * Create a new MCP configuration.
+ * @param {Object} params - Parameters for creating the MCP configuration
+ * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
+ * @param {Object} params.options - Configuration options
+ * @param {string} params.options.name - Unique name for the MCP configuration
+ * @param {boolean} [params.options.manuallyManageConnections] - Whether to use chat-based authentication or manually connect accounts
+ * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
+ *
+ * @example
+ * ```typescript
+ * const server = await composio.mcpConfig.create("personal-mcp-server", {
+ * toolkits: ["github", "slack"],
+ * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
+ * manuallyManageConnections: false
+ * }
+ * });
+ *
+ * const server = await composio.mcpConfig.create("personal-mcp-server", {
+ * toolkits: [{ toolkit: "gmail", authConfigId: "ac_243434343" }],
+ * allowedTools: ["GMAIL_FETCH_EMAILS"],
+ * manuallyManageConnections: false
+ * }
+ * });
+ * ```
+ */
+ async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
+ const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
+ if (config.error) {
+ throw new ValidationError('Invalid parameters passed to create mcp config', {
+ cause: config.error,
+ });
+ }
+
+ const toolkits: string[] = [];
+ const auth_config_ids: string[] = [];
+ const custom_tools: string[] = config.data.allowedTools ?? [];
+
+ // extract all the toolkits, authconfigs, and allowed tools to separate slugs
+ config.data.toolkits.forEach(toolkit => {
+ if (typeof toolkit === 'string') {
+ toolkits.push(toolkit);
+ } else if (toolkit.toolkit) {
+ toolkits.push(toolkit.toolkit);
+ } else if (toolkit.authConfigId) {
+ auth_config_ids.push(toolkit.authConfigId);
+ }
+ });
+
+ const server = await this.client.mcp.custom.create({
+ name,
+ toolkits,
+ auth_config_ids,
+ custom_tools,
+ // if manually manage account is set to true, disable composio account management tools
+ managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
+ });
+
+ const camelCaseServer = transform(server)
+ .with(MCPConfigResponseSchema)
+ .using(raw => ({
+ name: raw.name,
+ allowedTools: raw.allowed_tools,
+ id: raw.id,
+ authConfigIds: raw.auth_config_ids,
+ commands: raw.commands,
+ MCPUrl: raw.mcp_url,
+ }));
+
+ return {
+ ...camelCaseServer,
+ generate: async (userId: string): Promise<MCPServerInstance> => {
+ return await this.generate(userId, server.id, {
+ manuallyManageConnections: config.data.manuallyManageConnections,
+ });
+ },
+ };
+ }
+
+ /**
+ * List the MCP servers with optional filtering and pagination
+ * @param {Object} options - Filtering and pagination options
+ * @param {number} [options.page=1] - Page number for pagination (1-based)
+ * @param {number} [options.limit=10] - Maximum number of items to return per page
+ * @param {string[]} [options.toolkits=[]] - Array of toolkit names to filter by
+ * @param {string[]} [options.authConfigs=[]] - Array of auth configuration IDs to filter by
+ * @param {string} [options.name] - Filter by MCP server name (partial match)
+ * @returns {Promise<MCPListResponse>} Paginated list of MCP servers with metadata
+ *
+ * @example
+ * ```typescript
+ * // List all MCP servers
+ * const allServers = await composio.experimental.mcp.list({});
+ *
+ * // List with pagination
+ * const pagedServers = await composio.experimental.mcp.list({
+ * page: 2,
+ * limit: 5
+ * });
+ *
+ * // Filter by toolkit
+ * const githubServers = await composio.experimental.mcp.list({
+ * toolkits: ['github', 'slack']
+ * });
+ *
+ * // Filter by name
+ * const namedServers = await composio.experimental.mcp.list({
+ * name: 'personal'
+ * });
+ * ```
+ */
+ async list(options: MCPListParams): Promise<MCPListResponse> {
+ const { data: params, error } = MCPListParamsSchema.safeParse(options);
+ if (error) {
+ throw new ValidationError('Failed to validate list options', {
+ cause: error,
+ });
+ }
+
+ const listResponse = await this.client.mcp.list({
+ page_no: params.page,
+ limit: params.limit,
+ toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
+ auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
+ name: params.name,
+ });
+
+ const transformedListResponse = transform(listResponse)
+ .with(MCPListResponseSchema)
+ .using(raw => ({
+ currentPage: raw.current_page,
+ totalPages: raw.total_pages,
+ items: raw.items.map(item => ({
+ name: item.name,
+ allowedTools: item.allowed_tools,
+ id: item.id,
+ authConfigIds: item.auth_config_ids,
+ commands: item.commands,
+ MCPUrl: item.mcp_url,
+ toolkitIcons: item.toolkit_icons,
+ serverInstanceCount: item.server_instance_count,
+ toolkits: item.toolkits,
+ })),
+ }));
+
+ return transformedListResponse;
+ }
+
+ /**
+ * Retrieve detailed information about a specific MCP server by its ID
+ * @param {string} serverId - The unique identifier of the MCP server to retrieve
+ * @returns {Promise<MCPItem>} Complete MCP server details including configuration, tools, and metadata
+ *
+ * @example
+ * ```typescript
+ * // Get a specific MCP server by ID
+ * const server = await composio.experimental.mcp.get("mcp_12345");
+ *
+ * console.log(server.name); // "My Personal MCP Server"
+ * console.log(server.allowedTools); // ["GITHUB_CREATE_ISSUE", "SLACK_SEND_MESSAGE"]
+ * console.log(server.toolkits); // ["github", "slack"]
+ * console.log(server.serverInstanceCount); // 3
+ *
+ * // Access setup commands for different clients
+ * console.log(server.commands.claude); // Claude setup command
+ * console.log(server.commands.cursor); // Cursor setup command
+ * console.log(server.commands.windsurf); // Windsurf setup command
+ *
+ * // Use the MCP URL for direct connections
+ * const mcpUrl = server.MCPUrl;
+ * ```
+ *
+ * @throws {ValidationError} When the server ID is invalid or server not found
+ */
+ async get(serverId: string): Promise<MCPItem> {
+ const response = await this.client.mcp.retrieve(serverId);
+ return transformMCPItemResponse(response);
+ }
+
+ /**
+ * Delete an MCP server configuration permanently
+ * @param {string} serverId - The unique identifier of the MCP server to delete
+ * @returns {Promise<{id: string; deleted: boolean}>} Confirmation object with server ID and deletion status
+ *
+ * @example
+ * ```typescript
+ * // Delete an MCP server by ID
+ * const result = await composio.experimental.mcp.delete("mcp_12345");
+ *
+ * if (result.deleted) {
+ * console.log(`Server ${result.id} has been successfully deleted`);
+ * } else {
+ * console.log(`Failed to delete server ${result.id}`);
+ * }
+ *
+ * // Example with error handling
+ * try {
+ * const result = await composio.experimental.mcp.delete("mcp_12345");
+ * console.log("Deletion successful:", result);
+ * } catch (error) {
+ * console.error("Failed to delete MCP server:", error.message);
+ * }
+ *
+ * // Delete and verify from list
+ * await composio.experimental.mcp.delete("mcp_12345");
+ * const servers = await composio.experimental.mcp.list({});
+ * const serverExists = servers.items.some(server => server.id === "mcp_12345");
+ * console.log("Server still exists:", serverExists); // Should be false
+ * ```
+ *
+ * @throws {ValidationError} When the server ID is invalid or server not found
+ * @throws {Error} When the server cannot be deleted due to active connections or other constraints
+ *
+ * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
+ */
+ async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
+ return await this.client.mcp.delete(serverId);
+ }
+
+ /**
+ * Update an existing MCP server configuration with new settings
+ * @param {string} serverId - The unique identifier of the MCP server to update
+ * @param {Object} config - Update configuration parameters
+ * @param {string} [config.name] - New name for the MCP server
+ * @param {Array} [config.toolkits] - Updated toolkit configurations
+ * @param {string} [config.toolkits[].toolkit] - Toolkit identifier (e.g., "github", "slack")
+ * @param {string} [config.toolkits[].authConfigId] - Auth configuration ID for the toolkit
+ * @param {string[]} [config.toolkits[].allowedTools] - Specific tools to enable for this toolkit
+ * @param {boolean} [config.manuallyManageConnections] - Whether to manually manage account connections
+ * @returns {Promise<MCPItem>} Updated MCP server configuration with all details
+ *
+ * @example
+ * ```typescript
+ * // Update server name only
+ * const updatedServer = await composio.experimental.mcp.update("mcp_12345", {
+ * name: "My Updated MCP Server"
+ * });
+ *
+ * // Update toolkits and tools
+ * const serverWithNewTools = await composio.experimental.mcp.update("mcp_12345", {
+ * toolkits: [
+ * {
+ * toolkit: "github",
+ * authConfigId: "auth_abc123",
+ * allowedTools: ["GITHUB_CREATE_ISSUE", "GITHUB_LIST_REPOS"]
+ * },
+ * {
+ * toolkit: "slack",
+ * authConfigId: "auth_xyz789",
+ * allowedTools: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]
+ * }
+ * ]
+ * });
+ *
+ * // Update connection management setting
+ * const serverWithManualAuth = await composio.experimental.mcp.update("mcp_12345", {
+ * name: "Manual Auth Server",
+ * manuallyManageConnections: true
+ * });
+ *
+ * // Complete update example
+ * const fullyUpdatedServer = await composio.experimental.mcp.update("mcp_12345", {
+ * name: "Production MCP Server",
+ * toolkits: [
+ * {
+ * toolkit: "gmail",
+ * authConfigId: "auth_gmail_prod",
+ * }
+ * ],
+ * allowedTools: ["GMAIL_SEND_EMAIL", "GMAIL_FETCH_EMAILS"]
+ * manuallyManageConnections: false
+ * });
+ *
+ * console.log("Updated server:", fullyUpdatedServer.name);
+ * console.log("New tools:", fullyUpdatedServer.allowedTools);
+ * ```
+ *
+ * @throws {ValidationError} When the update parameters are invalid or malformed
+ * @throws {Error} When the server ID doesn't exist or update fails
+ *
+ * @note Only provided fields will be updated. Omitted fields will retain their current values.
+ * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
+ */
+ async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
+ const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
+ if (error) {
+ throw new ValidationError('Failed to validate update params', {
+ cause: error,
+ });
+ }
+
+ const toolkits: string[] = [];
+ const auth_config_ids: string[] = [];
+ const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
+
+ // extract all the toolkits, authconfigs, and allowed tools to separate slugs
+ params.toolkits?.forEach(toolkit => {
+ if (typeof toolkit === 'string') {
+ toolkits.push(toolkit);
+ } else if (toolkit.toolkit) {
+ toolkits.push(toolkit.toolkit);
+ } else if (toolkit.authConfigId) {
+ auth_config_ids.push(toolkit.authConfigId);
+ }
+ });
+ const response = await this.client.mcp.update(serverId, {
+ ...{ name: params.name ?? undefined },
+ ...(params.toolkits
+ ? {
+ custom_tools: custom_tools,
+ toolkits: toolkits,
+ auth_config_ids: auth_config_ids,
+ }
+ : {}),
+ ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
+ });
+ return transformMCPItemResponse(response);
+ }
+
+ /**
+ * Get server URLs for an existing MCP server.
+ * The response is wrapped according to the provider's specifications.
+ *
+ * @example
+ * ```typescript
+ * import { Composio } from "@composio/code";
+ *
+ * const composio = new Composio();
+ * const mcp = await composio.experimental.mcp.generate("default", "<mcp_config_id>");
+ * ```
+ *
+ * @param userId {string} external user id from your database for whom you want the server for
+ * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
+ * @param options {object} additional options
+ * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
+ */
+ async generate(
+ userId: string,
+ mcpConfigId: string,
+ options?: MCPGetInstanceParams
+ ): Promise<MCPServerInstance> {
+ const server = await this.client.mcp.retrieve(mcpConfigId);
+ const params = MCPGetInstanceParamsSchema.safeParse(
+ options ?? { manuallyManageConnections: false }
+ );
+ if (params.error) {
+ throw new ValidationError('Invalid params passed for Get Instance Params', {
+ cause: params.error,
+ });
+ }
+
+ const urlResponse = await this.client.mcp.generate.url({
+ mcp_server_id: mcpConfigId,
+ user_ids: [userId],
+ managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
+ });
+
+ const userIdsURL = urlResponse.user_ids_url[0];
+ const serverInstance = MCPServerInstanceSchema.safeParse({
+ id: server.id,
+ name: server.name,
+ type: 'streamable_http' as const,
+ url: userIdsURL,
+ userId: userId,
+ allowedTools: server.allowed_tools,
+ authConfigs: server.auth_config_ids,
+ });
+
+ if (serverInstance.error) {
+ throw new ValidationError('Failed to parse MCP server instance', {
+ cause: serverInstance.error,
+ });
+ }
+
+ return serverInstance.data;
+ }
+}
diff --git a/ts/packages/core/src/models/MCP.ts b/ts/packages/core/src/models/MCP.ts
index 35b657404..f2a744b2a 100644
--- a/ts/packages/core/src/models/MCP.ts
+++ b/ts/packages/core/src/models/MCP.ts
@@ -51,23 +51,15 @@ import { ConnectionRequest } from '../types/connectionRequest.types';
* Extract the MCP response type from a provider.
*/
type ExtractMcpResponseType<T> =
- T extends BaseComposioProvider<unknown, unknown, infer TMcp, unknown>
+ T extends BaseComposioProvider<unknown, unknown, infer TMcp>
? TMcp
: /* @default */ McpServerGetResponse;
-/**
- * Extract the experimental MCP response type from a provider.
- */
-type ExtractExperimentalMcpResponseType<T> =
- T extends BaseComposioProvider<unknown, unknown, unknown, infer TMcpExperimental>
- ? TMcpExperimental
- : /* @default */ McpServerGetResponse;
-
/**
* MCP (Model Control Protocol) class
* Handles MCP server operations
*/
-export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown>> {
+export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknown>> {
private client: ComposioClient;
private toolkits: Toolkits;
protected provider: TProvider;
@@ -775,6 +767,7 @@ export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknow
* @param serverName - Name of the MCP server
* @returns Transformed response in appropriate format
+ * @deprecated
*/
private wrapMcpServerResponse(
data: McpUrlResponseCamelCase,
@@ -885,82 +878,3 @@ export class MCP<TProvider extends BaseComposioProvider<unknown, unknown, unknow
return this.get(servers[0].id);
}
}
-
-/**
- * MCP (Model Control Protocol) class
- * Handles MCP server operations.
- * When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
- */
-export class ExperimentalMCP<
- TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown>,
-> {
- mcp: MCP<TProvider>;
- provider: TProvider;
- declare readonly TMcpExperimentalResponse: ExtractExperimentalMcpResponseType<TProvider>;
-
- constructor(client: ComposioClient, provider: TProvider) {
- this.mcp = new MCP(client, provider);
- this.provider = provider;
- telemetry.instrument(this);
- }
-
- /**
- * Get server URLs for an existing MCP server.
- * The response is wrapped according to the provider's specifications.
- *
- * @example
- * ```typescript
- * import { Composio } from "@composio/code";
- *
- * const composio = new Composio();
- * const server = await composio.experimental.mcp.getServer("default", "<mcp_config_id>");
- * ```
- *
- * @param userId {string} external user id from your database for whom you want the server for
- * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
- * @param options {object} additional options
- * @param options.limitTools {string[]} limit the tools to the ones specified
- * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
- */
- async getServer(
- userId: string,
- mcpConfigId: string,
- options?: {
- limitTools?: string[];
- isChatAuth?: boolean;
- }
- ): Promise<ReturnType<TProvider['wrapMcpServers']>> {
- return this.mcp.getServer(mcpConfigId, userId, options).then(res => {
- // TODO: investigate why this cast is needed in the first place.
- // Without it, this type is always inferred as `unknown`.
- return this.provider.wrapMcpServers(res) as ReturnType<TProvider['wrapMcpServers']>;
- });
- }
-
- /**
- * Get server URLs for an existing MCP server.
- *
- * @example
- * ```typescript
- * import { Composio } from "@composio/code";
- *
- * const composio = new Composio();
- * const server = await composio.experimental.mcp.getRawMCPServer("default", "<mcp_config_id>");
- * ```
- *
- * @param userId {string} external user id from your database for whom you want the server for
- * @param mcpConfigId {string} config id of the MCPConfig for which you want to create a server for
- * @param options.limitTools {string[]} limit the tools to the ones specified
- * @param options.isChatAuth {boolean} Authenticate the users via chat when they use the MCP Server
- */
- async getRawMCPServer(
- userId: string,
- mcpConfigId: string,
- options?: {
- limitTools?: string[];
- isChatAuth?: boolean;
- }
- ) {
- return await this.getServer(mcpConfigId, userId, options);
- }
-}
diff --git a/ts/packages/core/src/models/MCPConfig.ts b/ts/packages/core/src/models/MCPConfig.ts
deleted file mode 100644
index 591d92d12..000000000
--- a/ts/packages/core/src/models/MCPConfig.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import type { BaseComposioProvider } from '../provider/BaseProvider';
-import { telemetry } from '../telemetry/Telemetry';
-import type { McpServerCreateResponse, McpRetrieveResponse } from '../types/mcp.types';
-import type { MCP } from './MCP';
-
-/**
- * MCPConfig (Model Control Protocol Config) class
- * Handles CRUD operations related to MCP configurations.
- */
-export class MCPConfig<TProvider extends BaseComposioProvider<unknown, unknown, unknown, unknown>> {
- constructor(private mcp: MCP<TProvider>) {
- telemetry.instrument(this);
- }
-
- /**
- * Create a new MCP configuration.
- * @param {Object} params - Parameters for creating the MCP configuration
- * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
- * @param {Object} params.options - Configuration options
- * @param {string} params.options.name - Unique name for the MCP configuration
- * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
- * @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
- *
- * @example
- * ```typescript
- * const server = await composio.mcpConfig.create("personal-mcp-server", [
- * {
- * authConfigId: "ac_xyz",
- * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
- * }
- * ],
- * {
- * isChatAuth: true
- * }
- * });
- * ```
- */
- async create(
- name: string,
- serverConfig: Array<{
- authConfigId: string;
- allowedTools: string[];
- }>,
- options: {
- isChatAuth?: boolean;
- }
- ): Promise<McpServerCreateResponse<typeof this.mcp.TMcpResponse>> {
- return this.mcp.create(name, serverConfig, options);
- }
-
- /**
- * Get details of a specific MCP config by name
- * @param {string} configName - Config name
- * @returns {Promise<McpRetrieveResponse>} Server details
- * @throws {ValidationError} If no MCP Config found with the given name
- * @throws {ValidationError} If multiple MCP Configs found with the same name
- *
- * @example
- * ```typescript
- * const mcpConfig = await composio.mcpConfig.getByName('my-gmail-server');
- * ```
- */
- async getByName(configName: string): Promise<McpRetrieveResponse> {
- return this.mcp.getByName(configName);
- }
-
- /**
- * Get details of a specific MCP Config
- * @param {string} configId - Config UUID
- * @returns {Promise<McpRetrieveResponse>} Config details
- *
- * @example
- * ```typescript
- * const mcpConfig = await composio.mcpConfig.get('config-uuid');
- * ```
- */
- async get(configId: string): Promise<McpRetrieveResponse> {
- return this.mcp.get(configId);
- }
-}
diff --git a/ts/packages/core/src/models/ToolRouter.experimental.ts b/ts/packages/core/src/models/ToolRouter.experimental.ts
new file mode 100644
index 000000000..f914217f4
--- /dev/null
+++ b/ts/packages/core/src/models/ToolRouter.experimental.ts
@@ -0,0 +1,75 @@
+import { Composio as ComposioClient } from '@composio/client';
+import { telemetry } from '../telemetry/Telemetry';
+import {
+ ToolRouterConfig,
+ ToolRouterConfigSchema,
+ ToolRouterSession,
+ ToolRouterSessionSchema,
+} from '../types/toolRouter.types';
+import { ValidationError } from '../errors';
+import { transform } from '../utils/transform';
+
+export class ToolRouter {
+ constructor(private client: ComposioClient) {
+ this.client = client;
+ telemetry.instrument(this);
+ }
+
+ /**
+ * Creates a new Session for the tool router
+ *
+ * @param userId {string} The user id to create the session for
+ * @param routerConfig {ToolRouterConfig} The router config to use
+ * @returns {Promise<ToolRouterSession>} The tool router session
+ *
+ * @example
+ * ```typescript
+ * import { Composio } form "@composio/core"
+ *
+ * const composio = new Composio()
+ * const userId = "xxx-ooo-xxxx"
+ *
+ * const mcpSession = await composio.experimental.toolRouter.createSession(userId, {
+ * toolkits: ["github", "hackernews", "slack"]
+ * })
+ *
+ * // with auth configs
+ * const mcpSession = await composio.experimental.toolRouter.createSession(userId, {
+ * toolkits: [{ toolkit: "github", authConfingId: "ac_123455344"}]
+ * ```
+ */
+ async createSession(userId: string, routerConfig?: ToolRouterConfig): Promise<ToolRouterSession> {
+ const config = ToolRouterConfigSchema.safeParse(routerConfig ?? {});
+ if (config.error) {
+ throw new ValidationError('Failed to parse tool router config', {
+ cause: config.error,
+ });
+ }
+
+ const toolkitConfig = config.data.toolkits?.map(config => {
+ if (typeof config === 'string') {
+ return { toolkit: config };
+ } else {
+ return {
+ toolkit: config.toolkit,
+ auth_config_id: config.authConfigId,
+ };
+ }
+ });
+
+ const session = await this.client.toolRouter.createSession({
+ user_id: userId,
+ config: {
+ toolkits: toolkitConfig,
+ manually_manage_connections: config.data.manuallyManageConnections,
+ },
+ });
+
+ return transform(session)
+ .with(ToolRouterSessionSchema)
+ .using(raw => ({
+ sessionId: raw.session_id,
+ url: raw.chat_session_mcp_url,
+ }));
+ }
+}
diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.ts
index 5cdd05f8a..30c17e29b 100644
--- a/ts/packages/core/src/models/Tools.ts
+++ b/ts/packages/core/src/models/Tools.ts
@@ -57,7 +57,7 @@ import { getToolkitVersion } from '../utils/toolkitVersion';
export class Tools<
TToolCollection,
TTool,
- TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown, unknown>,
+ TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
> {
private client: ComposioClient;
private readonly customTools: CustomTools;
diff --git a/ts/packages/core/src/provider/BaseProvider.ts b/ts/packages/core/src/provider/BaseProvider.ts
index 9603fc47d..c0cbe1bcb 100644
--- a/ts/packages/core/src/provider/BaseProvider.ts
+++ b/ts/packages/core/src/provider/BaseProvider.ts
@@ -9,10 +9,7 @@ import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
* Base class for all providers.
* This class is not meant to be used directly, but rather to be extended by different provider implementations.
*/
-abstract class BaseProvider<
- TMcpResponse = McpServerGetResponse,
- TMcpExperimentalResponse = McpServerGetResponse,
-> {
+abstract class BaseProvider<TMcpResponse> {
/**
* @public
* The name of the provider.
@@ -73,12 +70,6 @@ abstract class BaseProvider<
* @returns Transformed response in provider-specific format, or undefined to use default transformation
*/
wrapMcpServerResponse?(data: McpUrlResponse): TMcpResponse;
-
- /**
- * This method replaces `wrapMcpServerResponse` when Composio's config contains has the
- * `experimental.mcp` flag enabled.
- */
- abstract wrapMcpServers(data: TMcpResponse): TMcpExperimentalResponse;
}
/**
@@ -90,8 +81,7 @@ export abstract class BaseNonAgenticProvider<
TToolCollection,
TTool,
TMcpResponse = McpServerGetResponse,
- TMcpExperimentalResponse = McpServerGetResponse,
-> extends BaseProvider<TMcpResponse, TMcpExperimentalResponse> {
+> extends BaseProvider<TMcpResponse> {
override readonly _isAgentic = false;
/**
@@ -116,9 +106,8 @@ export abstract class BaseNonAgenticProvider<
export abstract class BaseAgenticProvider<
TToolCollection,
TTool,
- TMcpResponse = McpServerGetResponse,
- TMcpExperimentalResponse = McpServerGetResponse,
-> extends BaseProvider<TMcpResponse, TMcpExperimentalResponse> {
+ TMcpResponse,
+> extends BaseProvider<TMcpResponse> {
override readonly _isAgentic = true;
/**
@@ -142,11 +131,6 @@ export abstract class BaseAgenticProvider<
* Base type for all providers.
* This type is used to infer the type of the provider from the provider implementation.
*/
-export type BaseComposioProvider<
- TToolCollection,
- TTool,
- TMcpResponse = McpServerGetResponse,
- TMcpExperimentalResponse = McpServerGetResponse,
-> =
- | BaseNonAgenticProvider<TToolCollection, TTool, TMcpResponse, TMcpExperimentalResponse>
- | BaseAgenticProvider<TToolCollection, TTool, TMcpResponse, TMcpExperimentalResponse>;
+export type BaseComposioProvider<TToolCollection, TTool, TMcpResponse = McpServerGetResponse> =
+ | BaseNonAgenticProvider<TToolCollection, TTool, TMcpResponse>
+ | BaseAgenticProvider<TToolCollection, TTool, TMcpResponse>;
diff --git a/ts/packages/core/src/provider/ComposioProvider.ts b/ts/packages/core/src/provider/ComposioProvider.ts
index 105efbaea..8b0ddd0a7 100644
--- a/ts/packages/core/src/provider/ComposioProvider.ts
+++ b/ts/packages/core/src/provider/ComposioProvider.ts
@@ -19,10 +19,6 @@ export class ComposioProvider extends BaseNonAgenticProvider<Array<CustomTool>,
super();
}
- override wrapMcpServers(data: McpServerGetResponse) {
- return data;
- }
-
wrapTool = (tool: Tool): CustomTool => {
return tool as CustomTool;
};
diff --git a/ts/packages/core/src/provider/OpenAIProvider.ts b/ts/packages/core/src/provider/OpenAIProvider.ts
index 606bcf24c..cfef7482c 100644
--- a/ts/packages/core/src/provider/OpenAIProvider.ts
+++ b/ts/packages/core/src/provider/OpenAIProvider.ts
@@ -14,7 +14,7 @@ import { Tool, ToolExecuteParams } from '../types/tool.types';
import logger from '../utils/logger';
import { ExecuteToolModifiers } from '../types/modifiers.types';
import { ExecuteToolFnOptions } from '../types/provider.types';
-import { McpUrlResponse, McpServerGetResponse, McpServerUrlInfo } from '../types/mcp.types';
+import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
export type OpenAiTool = OpenAI.ChatCompletionTool;
export type OpenAiToolCollection = Array<OpenAiTool>;
@@ -22,8 +22,7 @@ export type OpenAiToolCollection = Array<OpenAiTool>;
export class OpenAIProvider extends BaseNonAgenticProvider<
OpenAiToolCollection,
OpenAiTool,
- McpServerGetResponse,
- URL
+ McpServerGetResponse
> {
readonly name = 'openai';
@@ -58,29 +57,13 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
* @param data - The MCP URL response data
* @returns Standard MCP server response format
*/
- wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
+ override wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
return data.map(item => ({
url: new URL(item.url),
name: item.name,
}));
}
- override wrapMcpServers(servers: McpServerGetResponse): URL {
- function wrapMcpServer(server: McpServerUrlInfo) {
- return server.url;
- }
-
- if (Array.isArray(servers)) {
- if (servers.length === 0) {
- throw new Error('No servers found');
- }
-
- return wrapMcpServer(servers[0]);
- }
-
- return wrapMcpServer(servers);
- }
-
/**
* Wraps a Composio tool in the OpenAI function calling format.
*
diff --git a/ts/packages/core/src/types/authConfigs.types.ts b/ts/packages/core/src/types/authConfigs.types.ts
index bde5f5a3c..0060f94b1 100644
--- a/ts/packages/core/src/types/authConfigs.types.ts
+++ b/ts/packages/core/src/types/authConfigs.types.ts
@@ -17,6 +17,7 @@ export const AuthSchemeTypes = {
NO_AUTH: 'NO_AUTH',
BASIC_WITH_JWT: 'BASIC_WITH_JWT',
CALCOM_AUTH: 'CALCOM_AUTH',
+ SERVICE_ACCOUNT: 'SERVICE_ACCOUNT',
} as const;
export type AuthSchemeType = (typeof AuthSchemeTypes)[keyof typeof AuthSchemeTypes];
@@ -40,6 +41,7 @@ export const AuthSchemeEnum = z.enum([
'NO_AUTH',
'BASIC_WITH_JWT',
'CALCOM_AUTH',
+ 'SERVICE_ACCOUNT',
]);
export const CreateCustomAuthConfigParamsSchema = z.object({
type: z.literal('use_custom_auth'),
diff --git a/ts/packages/core/src/types/mcp.experimental.types.ts b/ts/packages/core/src/types/mcp.experimental.types.ts
new file mode 100644
index 000000000..2e3b2121d
--- /dev/null
+++ b/ts/packages/core/src/types/mcp.experimental.types.ts
@@ -0,0 +1,163 @@
+import z from 'zod';
+
+export const MCPServerInstanceSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ type: z.literal('streamable_http'),
+ url: z.string(),
+ userId: z.string(),
+ allowedTools: z.array(z.string()),
+ authConfigs: z.array(z.string()),
+});
+export type MCPServerInstance = z.infer<typeof MCPServerInstanceSchema>;
+
+/**
+ * MCP Create Method Input Types
+ */
+export const MCPConfigToolkitsSchema = z.object({
+ toolkit: z.string().describe('Id of the toolkit').optional(),
+ authConfigId: z.string().describe('Id of the auth config').optional(),
+});
+
+export const MCPConfigCreationParamsSchema = z.object({
+ toolkits: z.array(z.union([MCPConfigToolkitsSchema, z.string()])),
+ allowedTools: z.array(z.string()).optional(),
+ manuallyManageConnections: z
+ .boolean()
+ .default(false)
+ .optional()
+ .describe(
+ `Whether to manually manage accounts. If true, you need to manage accounts manually connect user accounts.
+If set to false, composio will inject account maangement tools into your mcp server for agents to request and authenticate accounts.
+defaults to false`
+ ),
+});
+export type MCPConfigCreationParams = z.infer<typeof MCPConfigCreationParamsSchema>;
+
+export const MCPConfigResponseSchema = z.object({
+ /**
+ * Unique identifier for the newly created custom MCP server
+ */
+ id: z.string(),
+
+ /**
+ * Human-readable name of the custom MCP server
+ */
+ name: z.string(),
+
+ /**
+ * List of tool identifiers that are enabled for this server
+ */
+ allowedTools: z.array(z.string()),
+
+ /**
+ * ID references to the auth configurations used by this server
+ */
+ authConfigIds: z.array(z.string()),
+
+ /**
+ * Set of command line instructions for connecting various clients to this MCP server
+ */
+ commands: z.object({
+ /**
+ * Command line instruction for Claude client setup
+ */
+ claude: z.string(),
+
+ /**
+ * Command line instruction for Cursor client setup
+ */
+ cursor: z.string(),
+
+ /**
+ * Command line instruction for Windsurf client setup
+ */
+ windsurf: z.string(),
+ }),
+
+ /**
+ * URL endpoint for establishing Server-Sent Events (SSE) connection to this MCP server
+ */
+ MCPUrl: z.string(),
+});
+
+export type MCPConfigResponse = z.infer<typeof MCPConfigResponseSchema>;
+export interface MCPConfigCreateResponse extends MCPConfigResponse {
+ /**
+ * Creates an instance for a user of the specific MCP Server/COnfig
+ * @param userId {string}
+ * @returns {MCPServerInstance}
+ */
+ generate: (userId: string) => Promise<MCPServerInstance>;
+}
+
+export const MCPGetInstanceParamsSchema = z.object({
+ manuallyManageConnections: z
+ .boolean()
+ .default(false)
+ .optional()
+ .describe(
+ `Whether to manually manage accounts. If true, you need to manage accounts manually connect user accounts.
+If set to false, composio will inject account maangement tools into your mcp server for agents to request and authenticate accounts.
+defaults to false`
+ ),
+});
+export type MCPGetInstanceParams = z.infer<typeof MCPGetInstanceParamsSchema>;
+
+export const MCPListParamsSchema = z.object({
+ page: z.number().optional().default(1),
+ limit: z.number().optional().default(10),
+ toolkits: z.array(z.string()).optional().default([]),
+ authConfigs: z.array(z.string()).optional().default([]),
+ name: z.string().optional(),
+});
+export type MCPListParams = z.infer<typeof MCPListParamsSchema>;
+
+export const MCPItemSchema = MCPConfigResponseSchema.extend({
+ ...z.object({
+ toolkitIcons: z.record(z.string(), z.string()),
+ serverInstanceCount: z.number(),
+ toolkits: z.array(z.string()),
+ }).shape,
+});
+export type MCPItem = z.infer<typeof MCPItemSchema>;
+export const MCPListResponseSchema = z.object({
+ items: z.array(MCPItemSchema),
+ currentPage: z.number(),
+ totalPages: z.number(),
+});
+export type MCPListResponse = z.infer<typeof MCPListResponseSchema>;
+
+export const MCPUpdateParamsSchema = z.object({
+ name: z.string().optional(),
+ toolkits: z.array(z.union([MCPConfigToolkitsSchema, z.string()])).optional(),
+ allowedTools: z.array(z.string()).optional(),
+ manuallyManageConnections: z
+ .boolean()
+ .optional()
+ .describe(
+ `Whether to manually manage accounts. If true, you need to manage accounts manually connect user accounts.
+If set to false, composio will inject account maangement tools into your mcp server for agents to request and authenticate accounts.
+defaults to false`
+ ),
+});
+export type MCPUpdateParams = z.infer<typeof MCPUpdateParamsSchema>;
+
+export const MCPServerConnectionStatus = z.object({
+ connected: z.boolean(),
+ toolkit: z.string(),
+ connectedAccountId: z.string(),
+});
+export type MCPServerConnectionStatus = z.infer<typeof MCPServerConnectionStatus>;
+
+export const MCPServerConnectedAccountsSchema = z.record(
+ z.string(),
+ z.array(
+ z.object({
+ toolkit: z.string(),
+ authConfigId: z.string(),
+ connectedAccountId: z.string(),
+ })
+ )
+);
+export type MCPServerConnectedAccounts = z.infer<typeof MCPServerConnectedAccountsSchema>;
diff --git a/ts/packages/core/src/types/mcp.types.ts b/ts/packages/core/src/types/mcp.types.ts
index d9ee21db8..ed92b4682 100644
--- a/ts/packages/core/src/types/mcp.types.ts
+++ b/ts/packages/core/src/types/mcp.types.ts
@@ -6,7 +6,7 @@ import {
import { z } from 'zod';
/**
- * MCP Create Method Input Types
+ * @deprecated
*/
export const MCPToolkitConfigSchema = z.object({
toolkit: z.string().min(1, 'Toolkit name cannot be empty'),
@@ -17,7 +17,9 @@ export const MCPToolkitConfigSchema = z.object({
});
export type MCPToolkitConfig = z.infer<typeof MCPToolkitConfigSchema>;
-
+/**
+ * @deprecated
+ */
export const MCPToolkitConfigsArraySchema = z
.array(MCPToolkitConfigSchema)
.min(1, 'At least one toolkit configuration is required')
@@ -27,10 +29,12 @@ export const MCPToolkitConfigsArraySchema = z
return uniqueToolkits.size === toolkits.length;
}, 'Duplicate toolkits are not allowed. Each toolkit must be unique.');
+/**
+ * @deprecated
+ */
export const MCPAuthOptionsSchema = z.object({
isChatAuth: z.boolean().optional(),
});
-
export type MCPAuthOptions = z.infer<typeof MCPAuthOptionsSchema>;
export const MCPGetServerParamsSchema = z
diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.ts
new file mode 100644
index 000000000..eb83b5d0e
--- /dev/null
+++ b/ts/packages/core/src/types/toolRouter.types.ts
@@ -0,0 +1,19 @@
+import z from 'zod';
+
+export const ToolRouterToolkitConfigSchema = z.object({
+ toolkit: z.string(),
+ authConfigId: z.string().optional(),
+});
+
+export const ToolRouterConfigSchema = z.object({
+ toolkits: z.array(z.union([z.string(), ToolRouterToolkitConfigSchema])).optional(),
+ manuallyManageConnections: z.boolean().optional(),
+});
+
+export type ToolRouterConfig = z.infer<typeof ToolRouterConfigSchema>;
+
+export const ToolRouterSessionSchema = z.object({
+ sessionId: z.string(),
+ url: z.string(),
+});
+export type ToolRouterSession = z.infer<typeof ToolRouterSessionSchema>;
diff --git a/ts/packages/core/src/types/toolkit.types.ts b/ts/packages/core/src/types/toolkit.types.ts
index b261e94e9..7be118ae8 100644
--- a/ts/packages/core/src/types/toolkit.types.ts
+++ b/ts/packages/core/src/types/toolkit.types.ts
@@ -58,8 +58,10 @@ export type ToolKitListResponse = z.infer<typeof ToolKitListResponseSchema>;
* Toolkit retrieve response
*/
export const ToolkitAuthFieldSchema = z.object({
- name: z.string(),
+ description: z.string(),
displayName: z.string(),
+ required: z.boolean(),
+ name: z.string(),
type: z.string(),
default: z.string().nullable().optional(),
});
diff --git a/ts/packages/core/src/utils/session.ts b/ts/packages/core/src/utils/session.ts
index 6ae6816c2..ca29df889 100644
--- a/ts/packages/core/src/utils/session.ts
+++ b/ts/packages/core/src/utils/session.ts
@@ -3,7 +3,7 @@ import { version } from '../../package.json';
import { ComposioRequestHeaders } from '../types/composio.types';
export function getSessionHeaders(
- provider: BaseComposioProvider<unknown, unknown, unknown, unknown> | undefined
+ provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
) {
return {
'x-source': provider?.name || '@composio/core',
@@ -14,7 +14,7 @@ export function getSessionHeaders(
export const getDefaultHeaders = (
headers: ComposioRequestHeaders | undefined,
- provider: BaseComposioProvider<unknown, unknown, unknown, unknown> | undefined
+ provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
) => {
const sessionHeaders = getSessionHeaders(provider);
return {
diff --git a/ts/packages/providers/anthropic/src/index.ts b/ts/packages/providers/anthropic/src/index.ts
index 3cd8ecbfa..29f11ea69 100644
--- a/ts/packages/providers/anthropic/src/index.ts
+++ b/ts/packages/providers/anthropic/src/index.ts
@@ -17,7 +17,6 @@ import {
McpUrlResponse,
} from '@composio/core';
import Anthropic from '@anthropic-ai/sdk';
-import { type MastraMCPServerDefinition } from '@mastra/mcp';
import { AnthropicTool, InputSchema } from './types';
export type AnthropicMcpServerGetResponse = {
@@ -55,7 +54,6 @@ export type AnthropicContentBlock = {
export class AnthropicProvider extends BaseNonAgenticProvider<
AnthropicToolCollection,
AnthropicTool,
- AnthropicMcpServerGetResponse,
AnthropicMcpServerGetResponse
> {
readonly name = 'anthropic';
@@ -132,15 +130,6 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
};
}
- /**
- * Note(jkomyno): right now, there's a strict dependency between the return type of this method
- * and the expected MCP client that will be used to retrieve the tools from it (`MCPClient` from `@mastra/mcp`).
- * Do we want to keep this for Anthropic?
- */
- override wrapMcpServers(servers: AnthropicMcpServerGetResponse): AnthropicMcpServerGetResponse {
- return servers;
- }
-
/**
* Wraps a list of Composio tools in the Anthropic format.
*
diff --git a/ts/packages/providers/cloudflare/src/index.ts b/ts/packages/providers/cloudflare/src/index.ts
index 95f8c20a4..5de686bfe 100644
--- a/ts/packages/providers/cloudflare/src/index.ts
+++ b/ts/packages/providers/cloudflare/src/index.ts
@@ -25,7 +25,6 @@ type AiToolCollection = Record<string, AiTextGenerationToolInput>;
export class CloudflareProvider extends BaseNonAgenticProvider<
AiToolCollection,
AiTextGenerationToolInput,
- McpServerGetResponse,
McpServerGetResponse
> {
readonly name = 'cloudflare';
@@ -69,10 +68,6 @@ export class CloudflareProvider extends BaseNonAgenticProvider<
})) as McpServerGetResponse;
}
- override wrapMcpServers(data: McpServerGetResponse): McpServerGetResponse {
- return data;
- }
-
/**
* Wraps a Composio tool in the Cloudflare AI format.
*
diff --git a/ts/packages/providers/google/src/index.ts b/ts/packages/providers/google/src/index.ts
index 481f0f036..d410e7854 100644
--- a/ts/packages/providers/google/src/index.ts
+++ b/ts/packages/providers/google/src/index.ts
@@ -15,7 +15,6 @@ import {
ExecuteToolFnOptions,
McpUrlResponse,
McpServerGetResponse,
- McpServerUrlInfo,
} from '@composio/core';
import { FunctionDeclaration, Schema } from '@google/genai';
@@ -46,8 +45,7 @@ export type GoogleGenAIToolCollection = GoogleTool[];
export class GoogleProvider extends BaseNonAgenticProvider<
GoogleGenAIToolCollection,
GoogleTool,
- McpServerGetResponse,
- URL
+ McpServerGetResponse
> {
readonly name = 'google';
@@ -92,22 +90,6 @@ export class GoogleProvider extends BaseNonAgenticProvider<
})) as McpServerGetResponse;
}
- override wrapMcpServers(servers: McpServerGetResponse): URL {
- function wrapMcpServer(server: McpServerUrlInfo) {
- return server.url;
- }
-
- if (Array.isArray(servers)) {
- if (servers.length === 0) {
- throw new Error('No servers found');
- }
-
- return wrapMcpServer(servers[0]);
- }
-
- return wrapMcpServer(servers);
- }
-
/**
* Wraps a Composio tool in the Google GenAI function declaration format.
*
diff --git a/ts/packages/providers/langchain/src/index.ts b/ts/packages/providers/langchain/src/index.ts
index d90a76225..25eef11ae 100644
--- a/ts/packages/providers/langchain/src/index.ts
+++ b/ts/packages/providers/langchain/src/index.ts
@@ -23,7 +23,6 @@ export type LangChainToolCollection = Array<DynamicStructuredTool>;
export class LangchainProvider extends BaseAgenticProvider<
LangChainToolCollection,
DynamicStructuredTool,
- McpServerGetResponse,
McpServerGetResponse
> {
readonly name = 'langchain';
@@ -69,10 +68,6 @@ export class LangchainProvider extends BaseAgenticProvider<
})) as McpServerGetResponse;
}
- override wrapMcpServers(data: McpServerGetResponse): McpServerGetResponse {
- return data;
- }
-
/**
* Wraps a Composio tool in the Langchain DynamicStructuredTool format.
*
diff --git a/ts/packages/providers/mastra/src/index.ts b/ts/packages/providers/mastra/src/index.ts
index e14862eb8..f45e787fd 100644
--- a/ts/packages/providers/mastra/src/index.ts
+++ b/ts/packages/providers/mastra/src/index.ts
@@ -15,7 +15,6 @@ import {
removeNonRequiredProperties,
} from '@composio/core';
import { createTool } from '@mastra/core';
-import { type MastraMCPServerDefinition } from '@mastra/mcp';
export type MastraTool = ReturnType<typeof createTool>;
@@ -30,8 +29,7 @@ export interface MastraUrlMap {
export class MastraProvider extends BaseAgenticProvider<
MastraToolCollection,
MastraTool,
- MastraUrlMap,
- Record<string, MastraMCPServerDefinition>
+ MastraUrlMap
> {
readonly name = 'mastra';
private strict: boolean | null;
@@ -78,12 +76,6 @@ export class MastraProvider extends BaseAgenticProvider<
}, {});
}
- override wrapMcpServers(urls: MastraUrlMap) {
- return Object.fromEntries(
- Object.entries(urls).map(([key, value]) => [key, { url: new URL(value.url) }])
- ) satisfies Record<string, MastraMCPServerDefinition>;
- }
-
wrapTool(tool: Tool, executeTool: ExecuteToolFn): MastraTool {
const inputParams = tool.inputParameters;
diff --git a/ts/packages/providers/openai-agents/src/index.ts b/ts/packages/providers/openai-agents/src/index.ts
index 02e3be3e4..930fdacd0 100644
--- a/ts/packages/providers/openai-agents/src/index.ts
+++ b/ts/packages/providers/openai-agents/src/index.ts
@@ -16,18 +16,15 @@ import {
ExecuteToolFn,
McpUrlResponse,
McpServerGetResponse,
- McpServerUrlInfo,
} from '@composio/core';
-import type { HostedMCPTool, Tool as OpenAIAgentTool } from '@openai/agents';
-import { tool as createOpenAIAgentTool, hostedMcpTool } from '@openai/agents';
+import type { Tool as OpenAIAgentTool } from '@openai/agents';
+import { tool as createOpenAIAgentTool } from '@openai/agents';
type OpenAIAgentsToolCollection = Array<OpenAIAgentTool>;
-type TMcpExperimentalResponse = Array<HostedMCPTool<unknown>>;
export class OpenAIAgentsProvider extends BaseAgenticProvider<
OpenAIAgentsToolCollection,
OpenAIAgentTool,
- McpServerGetResponse,
- TMcpExperimentalResponse
+ McpServerGetResponse
> {
readonly name = 'openai-agents';
private strict: boolean | null;
@@ -74,32 +71,6 @@ export class OpenAIAgentsProvider extends BaseAgenticProvider<
})) as McpServerGetResponse;
}
- override wrapMcpServers(servers: McpServerGetResponse): TMcpExperimentalResponse {
- const prefixes = Object.keys(servers);
-
- function removePrefix(str: string): string {
- for (const prefix of prefixes) {
- if (str.startsWith(prefix)) {
- return str.slice(prefix.length + 1);
- }
- }
- return str;
- }
-
- function wrapMcpServer({ name, url }: McpServerUrlInfo) {
- return hostedMcpTool({
- serverLabel: removePrefix(name),
- serverUrl: url.toString(),
- });
- }
-
- if (Array.isArray(servers)) {
- return servers.map(server => wrapMcpServer(server));
- }
-
- return [wrapMcpServer(servers)];
- }
-
/**
* Wraps a Composio tool in a OpenAI Agents tool format.
*
diff --git a/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts b/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
index 0750222d9..ae1e0ab97 100644
--- a/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+++ b/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
@@ -34,15 +34,9 @@ export type OpenAIResponsesProviderOptions = {
/**
* OpenAI-specific MCP server response format
*/
-export interface OpenAIMcpServerResponse {
- type: 'mcp';
- server_label: string;
- server_url: string;
-}
export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
OpenAiToolCollection,
OpenAiTool,
- OpenAiMcpTool[],
OpenAiMcpTool[]
> {
readonly name = 'openai';
@@ -86,7 +80,7 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
* @param serverName - Name of the MCP server
* @returns OpenAI-specific MCP server response format
*/
- wrapMcpServerResponse(data: McpUrlResponse): OpenAiMcpTool[] {
+ override wrapMcpServerResponse(data: McpUrlResponse): OpenAiMcpTool[] {
console.log('Wrapping MCP server response', data);
return data.map(item => ({
type: 'mcp',
@@ -96,10 +90,6 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
}));
}
- override wrapMcpServers(servers: OpenAiMcpTool[]): OpenAiMcpTool[] {
- return servers;
- }
-
/**
* Wraps a Composio tool in the OpenAI function calling format.
*
diff --git a/ts/packages/providers/vercel/src/index.ts b/ts/packages/providers/vercel/src/index.ts
index cf5772b21..42310a8b2 100644
--- a/ts/packages/providers/vercel/src/index.ts
+++ b/ts/packages/providers/vercel/src/index.ts
@@ -18,7 +18,6 @@ import {
McpServerGetResponse,
removeNonRequiredProperties,
jsonSchemaToZodSchema,
- McpServerUrlInfo,
} from '@composio/core';
import type { Tool as VercelTool } from 'ai';
import { tool } from 'ai';
@@ -27,8 +26,7 @@ export type VercelToolCollection = Record<string, VercelTool>;
export class VercelProvider extends BaseAgenticProvider<
VercelToolCollection,
VercelTool,
- McpServerGetResponse,
- URL
+ McpServerGetResponse
> {
readonly name = 'vercel';
private strict: boolean | null;
@@ -58,22 +56,6 @@ export class VercelProvider extends BaseAgenticProvider<
this.strict = strict;
}
- override wrapMcpServers(servers: McpServerGetResponse): URL {
- function wrapMcpServer(server: McpServerUrlInfo) {
- return server.url;
- }
-
- if (Array.isArray(servers)) {
- if (servers.length === 0) {
- throw new Error('No servers found');
- }
-
- return wrapMcpServer(servers[0]);
- }
-
- return wrapMcpServer(servers);
- }
-
/**
* Wraps a Composio tool in a Vercel AI SDK tool format.
*