Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat: update mcp flow in ts sdk
Utkarsh Dixit2e46ed5614d3
diff --git a/fern/pages/src/mcp/developers.mdx b/fern/pages/src/mcp/developers.mdxindex 12a89958d..e16942312 100644--- a/fern/pages/src/mcp/developers.mdx+++ b/fern/pages/src/mcp/developers.mdx@@ -6,84 +6,210 @@ keywords: ""hide-nav-links: true-----## Introduction-Composio MCP lets you build custom MCP servers that your users can connect to and use to perform actions.You can manage these servers via our [Dashboard](https://app.composio.dev), or use the [SDK/API](/api-reference/mcp) for greater control and flexibility.## Creating MCP Servers and Onboarding End users<Steps><Step title="Configure Authentication">- - **Configure Toolkit permissions:**- Select the specific scopes and permissions your integration requires for each connected application. This ensures your MCP server has the right level of access.+ - **Create and Configure Toolkit permissions:**+ - Select the specific scopes and permissions your integration requires for each connected application. This ensures your MCP server has the right level of access.+ - Check this guide on what auth config is and how to configue it - [Auth Config setup guide](/docs/custom-auth-configs)- **Customize the authentication experience (Optional):**- Create a seamless, branded experience by providing your own OAuth credentials and customizing the consent screens.-- **Learn more:**- - [Integration setup guide](/docs/custom-auth-configs) - Detailed walkthrough of configuring app integrations- - [Custom auth configs](/docs/custom-auth-configs) - Instructions for customizing the authentication+ - Create a seamless, branded experience by providing your own OAuth credentials and customizing the consent screens.+ - Learn more here - [Custom auth configs](/docs/custom-auth-configs)</Step><Step title="Create and configure an MCP server">- Making the following request:- ```bash- curl -X POST https://backend.composio.dev/api/v3/mcp/servers \- -H "x-api-key: <YOUR_API_KEY>" \- -H "Content-Type: application/json" \- -d '{- "name": "Gmail MCP Server",- "allowed_tools": [- "GMAIL_FETCH_EMAIL",- "GMAIL_CREATE_EMAIL_DRAFT",- ],- "auth_config_ids": ["ac_auth_12"]- }'- ```- The response looks like:++ ```typescript+ import { Composio } from '@composio/core';- ```json- {- "id": "5bc757cc-7a8e-431c-8616-7f57cbed2423",- "name": "Gmail MCP Server"",- "auth_config_ids": ["ac_auth_12"],- "allowed_tools": [- "GMAIL_FETCH_EMAIL",- "GMAIL_CREATE_EMAIL_DRAFT",+ const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ });++ // Create an MCP server with the new API structure+ const mcpConfig = await composio.mcp.create({+ name: "Gmail MCP Server",+ serverConfig: [+ {+ authConfigId: "ac_auth_12", // Your auth config ID+ allowedTools: [+ "GMAIL_FETCH_EMAILS",+ "GMAIL_CREATE_EMAIL_DRAFT",+ "GMAIL_SEND_EMAIL"+ ]+ }],- "mcp_url": "https://mcp.composio.dev/composio/server/5bc757cc-7a8z-431c-8616-7f57cbed2421?transport=sse",- "commands": {- "cursor": "npx @composio/mcp@latest setup \"<mcp_url>\" --client cursor",- "claude": "npx @composio/mcp@latest setup \"<mcp_url>\" --client claude",- "windsurf": "npx @composio/mcp@latest setup \"<mcp_url>\" --client windsurf"- },- "created_at": "2025-05-18T22:15:25.926Z",- "updated_at": "2025-05-18T22:15:25.926Z",- "managed_auth_via_composio": false- }+ options: {+ isChatAuth: true // Enable chat-based authentication+ }+ });++ console.log(`✅ MCP server created: ${mcpConfig.id}`);+ console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);+ ```+ </Step>+ <Step title="Generate server URLs for users">+ **Using the SDK:**+ ```typescript+ // Get server URLs for a specific user+ const serverUrls = await composio.mcp.getServer({+ id: mcpConfig.id,+ userId: "[email protected]",+ options: {+ limitTools: ["GMAIL_FETCH_EMAILS"], // Optional: limit to specific tools+ isChatAuth: true+ }+ });++ console.log("Server URLs:", serverUrls);+ ```++ **Using the convenience method (from create response):**+ ```typescript+ // Use the convenience method on the created server+ const serverUrls = await mcpConfig.getServer({+ userId: "[email protected]"+ });```</Step><Step title="Client applications connect to the server">- The resultant `mcp_url`; (`https://mcp.composio.dev/composio/server/<UUID>/mcp`) is used by the client applications to connect to the server.- The URL accepts three optional query parameters:+ The generated server URLs can be used directly by MCP clients. The URLs automatically handle user authentication and tool access based on your server configuration.-| Query param | Purpose |-|-------------|---------|-| `user_id` | Bind the session to a user identifier from your app. |-| `connected_account_id` | Pin the session to a specific Composio `connectedAccount` (skip account selection). |-| `include_composio_helper_actions=true` | Inject helper tools so the agent can walk the user through authentication when needed. |+ **Example server URL structure:**+ ```+ https://mcp.composio.dev/composio/server/<UUID>/[email protected]+ ```+ **Optional query parameters:**+ | Query param | Purpose |+ |-------------|---------|+ | `user_id` | Bind the session to a user identifier from your app |+ | `connected_account_id` | Pin the session to a specific Composio connected account |+ | `include_composio_helper_actions=true` | Include helper tools for agent-guided authentication |</Step></Steps>+## Managing MCP Servers++### Check User Connection Status++Before using an MCP server, you can check if a user has the necessary connected accounts:++```typescript+// Check if a user has connected accounts for all required toolkits+const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: mcpConfig.id,+ userId: "[email protected]"+});++console.log("Overall connection status:", connectionStatus.connected);+console.log("Individual toolkit status:", connectionStatus.connectedToolkits);++// Handle missing connections+if (!connectionStatus.connected) {+ Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {+ if (!status.connected) {+ console.log(`❌ ${toolkit} not connected`);+ // Guide user through authentication+ }+ });+}+```++### Find Servers by Name++```typescript+// Retrieve a server by its name+const serverDetails = await composio.mcp.getByName("Gmail MCP Server");+console.log("Server details:", serverDetails);+```++### List All Servers++```typescript+// List servers with filtering options+const servers = await composio.mcp.list({+ page: 1,+ limit: 10,+ toolkits: ["gmail", "slack"], // Filter by toolkits+ name: "production" // Filter by name+});++console.log("Found servers:", servers.items);+```++### Update Server Configuration++```typescript+// Update an existing server (uses traditional API signature)+const updatedServer = await composio.mcp.update(+ "server-uuid",+ "Updated Gmail Server",+ [+ {+ toolkit: "gmail",+ authConfigId: "ac_new_auth_config",+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]+ }+ ],+ { useComposioManagedAuth: true }+);+```++## Authentication Configuration++### Option 1: Pre-authenticate Users (Recommended)++Authenticate users upfront via the Composio SDK/API before they use the MCP server:++```typescript+// Check what authentication is needed+const authParams = await composio.mcp.getConnectionParams({+ id: mcpConfig.id,+ toolkit: "gmail"+});++// Initiate authentication for a user+const authRequest = await composio.mcp.authorize({+ id: mcpConfig.id,+ userId: "[email protected]",+ toolkit: "gmail"+});++if (authRequest.redirectUrl) {+ console.log("Please complete authentication:", authRequest.redirectUrl);+}+```++### Option 2: Agent-guided Authentication++Let the agent authenticate users on-demand by including helper actions:++```typescript+const serverUrls = await composio.mcp.getServer({+ id: mcpConfig.id,+ userId: "[email protected]"+});++// The server URLs will include helper actions that guide users through authentication+```+<Tip>- SSE support will be deprecated soon. To use the latest protocol, if you are using `/sse` or the `transport=sse` query parameter, change your endpoint to use `/mcp` and remove the transport query parameter.+Pre-authentication is recommended for production applications as it provides better user experience and more predictable behavior.</Tip>-### Configuring authentication-You or your users need to authenticate against an app to use it's MCP server through Composio!-This can be done in two ways:+## Best Practices++1. **Use meaningful server names** - This helps with organization and makes servers easier to find+2. **Limit tools appropriately** - Only include the tools your users actually need+3. **Check connection status** - Always verify user authentication before using server URLs+4. **Handle authentication gracefully** - Provide clear instructions when users need to authenticate+5. **Use the convenience methods** - The `getServer` method on create responses simplifies URL generation-* Authenticate users upfront via the Composio SDK/API. Follow [custom auth configs](/docs/custom-auth-configs) to learn how to connect users. This is recommended for most use cases-* Let the agent authenticate users on demand. Passing `include_composio_helper_actions=true` in the URL will include Composio's helper actions and the agent will guide the user through auth on demand.+<Warning>+SSE support is deprecated. If you're using `/sse` endpoints or `transport=sse` query parameters, migrate to the standard `/mcp` endpoints.+</Warning>diff --git a/fern/pages/src/mcp/introduction.mdx b/fern/pages/src/mcp/introduction.mdxindex cb14e4c8c..69aa89f50 100644--- a/fern/pages/src/mcp/introduction.mdx+++ b/fern/pages/src/mcp/introduction.mdx@@ -1,91 +1,450 @@----title: Composio MCP Servers-subtitle: "Guide to working with Composio MCP servers"-image: "https://og.composio.dev/api/og?title=Composio%20MCP%20Servers" # image for socials-keywords: ""+title: Composio MCP Introduction+subtitle: "Complete guide to using Composio MCP servers"+image: "https://og.composio.dev/api/og?title=Composio%20MCP%20Introduction"+keywords: "MCP, Model Context Protocol, Composio, SDK, TypeScript"hide-nav-links: true----Composio MCP (Model Control Protocol) servers provide a powerful way to expose and integrate tools from various applications, making them accessible to any compatible MCP client or SDK. This creates a seamless bridge between your tools and AI agents, enabling rich, interactive functionality across your ecosystem.--To learn about the MCP clients, see the MCP documentation.-To build with agents, one can customize the MCP server too.--<Tip>-Interested in embedding Composio MCP servers into your MCP clients or applications? Reach out via Slack or [Contact us](mailto:[email protected]) to get started!-</Tip>--## Creating Custom MCP Servers-<Steps>- <Step title="Configure Authentication">- - **Configure app permissions:**- Select the specific scopes and permissions your integration requires for each connected application. This ensures your MCP server has the right level of access.-- - **Customize the authentication experience (Optional):**- Create a seamless, branded experience by providing your own OAuth credentials and customizing the consent screens.-- **Learn more:**- - [Integration setup guide](/docs/custom-auth-configs) - Detailed walkthrough of configuring app integrations- - [Custom auth configs](/docs/custom-auth-configs) - Instructions for customizing the authentication- </Step>- <Step title="Create and configure an MCP server">- Making the following request:- ```bash- curl -X POST https://backend.composio.dev/api/v3/mcp/servers \- -H "x-api-key: <YOUR_API_KEY>" \- -H "Content-Type: application/json" \- -d '{- "name": "Gmail MCP Server",- "allowed_tools": [- "GMAIL_FETCH_EMAIL",- "GMAIL_CREATE_EMAIL_DRAFT",- ],- "auth_config_ids": ["ac_auth_12"]- }'- ```- The response looks like:-- ```json++## What is Composio MCP?++[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open protocol that standardizes how LLM-powered applications provide tools and context to underlying models. Composio MCP servers make all [Composio tools](/tools) available through this standardized protocol, enabling seamless integration with MCP-compatible clients.++## Key Features++- **🔧 1000+ Tools**: Access to all Composio tools through MCP+- **🔐 Managed Authentication**: Streamlined user authentication and account management+- **🌍 Multi-Framework Support**: Works with Claude, Anthropic, OpenAI, Mastra, and more+- **📊 Connection Monitoring**: Real-time status tracking for user connections+- **⚡ Easy Setup**: Simple SDK with intuitive named object arguments+- **🎯 Flexible Configuration**: Fine-grained control over tools and permissions++## Quick Start++### Installation++```bash+npm install @composio/core+```++### Basic Usage++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++// Create an MCP server+const mcpServer = await composio.mcp.create({+ name: "My Gmail Server",+ serverConfig: [+ {+ authConfigId: "ac_your_auth_config_id",+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]+ }+ ],+ options: {+ isChatAuth: true+ }+});++// Get server URLs for a user+const serverUrls = await mcpServer.getServer({+ userId: "[email protected]"+});++console.log("MCP Server URLs:", serverUrls);+```++## Complete API Reference++### Creating MCP Servers++The `create` method uses named object arguments for clear, readable configuration:++```typescript+const mcpServer = await composio.mcp.create({+ name: string, // Unique server name+ serverConfig: Array<{ // Auth configurations+ authConfigId: string, // Your auth config ID+ allowedTools: string[] // List of tool names+ }>,+ options: {+ isChatAuth?: boolean // Enable chat-based auth (default: false)+ }+});+```++**Complete Example:**++```typescript+const mcpServer = await composio.mcp.create({+ name: "Multi-Service Productivity Server",+ serverConfig: [+ {+ authConfigId: "ac_gmail_config",+ allowedTools: [+ "GMAIL_FETCH_EMAILS",+ "GMAIL_SEND_EMAIL",+ "GMAIL_CREATE_DRAFT"+ ]+ },+ {+ authConfigId: "ac_slack_config",+ allowedTools: [+ "SLACK_SEND_MESSAGE",+ "SLACK_GET_CHANNELS"+ ]+ }+ ],+ options: {+ isChatAuth: true+ }+});++console.log(`✅ Server created: ${mcpServer.id}`);+console.log(`📦 Toolkits: ${mcpServer.toolkits.join(", ")}`);+```++### Generating Server URLs++The `getServer` method provides URLs for MCP clients to connect:++```typescript+const serverUrls = await composio.mcp.getServer({+ id: string, // Server ID+ userId: string, // User identifier+ options?: {+ limitTools?: string[], // Subset of tools to include+ isChatAuth?: boolean // Override chat auth setting+ }+});+```++**Examples:**++```typescript+// Basic usage+const basicUrls = await composio.mcp.getServer({+ id: "mcp_server_id",+ userId: "[email protected]"+});++// With tool limitations+const limitedUrls = await composio.mcp.getServer({+ id: "mcp_server_id",+ userId: "[email protected]",+ options: {+ limitTools: ["GMAIL_FETCH_EMAILS"], // Only allow email fetching+ isChatAuth: false+ }+});++// Using convenience method (from create response)+const convenientUrls = await mcpServer.getServer({+ userId: "[email protected]"+});+```++### Checking User Connection Status++Before using an MCP server, check if users have the required connected accounts:++```typescript+const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: string, // Server ID+ userId: string // User identifier+});++// Returns: McpUserConnectionStatus+{+ type: "CONNECTED" | "DISCONNECTED",+ connected: boolean,+ connectedToolkits: {+ [toolkitName: string]: {+ type: "CONNECTED" | "DISCONNECTED",+ connected: boolean,+ toolkit: string,+ connectedAccountId?: string // Present if connected+ }+ }+}+```++**Complete Example:**++```typescript+const status = await composio.mcp.getUserConnectionStatus({+ id: mcpServer.id,+ userId: "[email protected]"+});++console.log(`Overall status: ${status.connected ? "✅ Ready" : "❌ Needs auth"}`);++// Handle missing connections+if (!status.connected) {+ for (const [toolkit, toolkitStatus] of Object.entries(status.connectedToolkits)) {+ if (!toolkitStatus.connected) {+ console.log(`❌ ${toolkit} requires authentication`);++ // Get authentication parameters+ const authParams = await composio.mcp.getConnectionParams({+ id: mcpServer.id,+ toolkit+ });++ // Initiate authentication+ const authRequest = await composio.mcp.authorize({+ id: mcpServer.id,+ userId: "[email protected]",+ toolkit+ });++ if (authRequest.redirectUrl) {+ console.log(`🔗 Authenticate here: ${authRequest.redirectUrl}`);+ }+ } else {+ console.log(`✅ ${toolkit} connected (${toolkitStatus.connectedAccountId})`);+ }+ }+}+```++### Managing Existing Servers++#### Find Servers by Name++```typescript+const server = await composio.mcp.getByName("My Gmail Server");+console.log(`Found server: ${server.id}`);+```++#### List All Servers++```typescript+const servers = await composio.mcp.list({+ page: 1,+ limit: 10,+ toolkits: ["gmail", "slack"], // Filter by toolkits+ authConfigs: ["ac_123"], // Filter by auth configs+ name: "production" // Filter by name pattern+});++console.log(`Found ${servers.items?.length} servers`);+```++#### Get Server Details++```typescript+const serverDetails = await composio.mcp.get("mcp_server_id");+console.log("Server details:", serverDetails);+```++#### Update Server Configuration++```typescript+const updatedServer = await composio.mcp.update(+ "mcp_server_id",+ "Updated Server Name",+ [{- "id": "5bc757cc-7a8e-431c-8616-7f57cbed2423",- "name": "Gmail MCP Server"",- "auth_config_ids": ["ac_auth_12"],- "allowed_tools": [- "GMAIL_FETCH_EMAIL",- "GMAIL_CREATE_EMAIL_DRAFT",+ toolkit: "gmail",+ authConfigId: "ac_new_config",+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]+ }+ ],+ { useComposioManagedAuth: true }+);+```++#### Delete Server++```typescript+const deleteResult = await composio.mcp.delete("mcp_server_id");+console.log("Server deleted:", deleteResult.deleted);+```++## Authentication Workflows++### Pre-Authentication (Recommended)++Authenticate users before they use the MCP server:++```typescript+// 1. Check what's needed+const authParams = await composio.mcp.getConnectionParams({+ id: mcpServer.id,+ toolkit: "gmail"+});++console.log("Required fields:", authParams.required_fields);++// 2. Initiate authentication+const authRequest = await composio.mcp.authorize({+ id: mcpServer.id,+ userId: "[email protected]",+ toolkit: "gmail"+});++// 3. Direct user to authentication URL+if (authRequest.redirectUrl) {+ console.log("Please visit:", authRequest.redirectUrl);+}++// 4. Verify connection after user completes auth+const finalStatus = await composio.mcp.getUserConnectionStatus({+ id: mcpServer.id,+ userId: "[email protected]"+});++if (finalStatus.connected) {+ console.log("✅ All toolkits connected, ready to use!");+}+```++### Agent-Guided Authentication++Let the agent handle authentication on-demand:++```typescript+const serverUrls = await composio.mcp.getServer({+ id: mcpServer.id,+ userId: "[email protected]",+ options: {+ isChatAuth: true // Include helper actions for authentication+ }+});++// The agent can now guide users through authentication as needed+```++## Real-World Example: Complete Gmail Integration++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+});++async function setupGmailMCP(userId: string) {+ // 1. Check if server already exists+ let gmailServer;+ try {+ gmailServer = await composio.mcp.getByName("Production Gmail Server");+ console.log("✅ Using existing server");+ } catch (error) {+ // 2. Create new server if it doesn't exist+ console.log("📦 Creating new Gmail server...");+ gmailServer = await composio.mcp.create({+ name: "Production Gmail Server",+ serverConfig: [+ {+ authConfigId: process.env.GMAIL_AUTH_CONFIG_ID!,+ allowedTools: [+ "GMAIL_FETCH_EMAILS",+ "GMAIL_SEND_EMAIL",+ "GMAIL_CREATE_DRAFT",+ "GMAIL_SEARCH_EMAILS"+ ]+ }],- "mcp_url": "https://mcp.composio.dev/composio/server/5bc757cc-7a8z-431c-8616-7f57cbed2421?transport=sse",- "commands": {- "cursor": "npx @composio/mcp@latest setup \"<mcp_url>\" --client cursor",- "claude": "npx @composio/mcp@latest setup \"<mcp_url>\" --client claude",- "windsurf": "npx @composio/mcp@latest setup \"<mcp_url>\" --client windsurf"- },- "created_at": "2025-05-18T22:15:25.926Z",- "updated_at": "2025-05-18T22:15:25.926Z",- "managed_auth_via_composio": false+ options: {+ isChatAuth: true+ }+ });+ }++ // 3. Check user connection status+ const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: gmailServer.id,+ userId+ });++ // 4. Handle authentication if needed+ if (!connectionStatus.connected) {+ console.log("🔐 User needs to authenticate with Gmail");++ const authRequest = await composio.mcp.authorize({+ id: gmailServer.id,+ userId,+ toolkit: "gmail"+ });++ return {+ server: gmailServer,+ needsAuth: true,+ authUrl: authRequest.redirectUrl+ };+ }++ // 5. Generate server URLs for MCP client+ const serverUrls = await gmailServer.getServer({+ userId,+ options: {+ limitTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]}- ```- </Step>- <Step title="Client applications connect to the server">- The resultant `mcp_url`; (`https://mcp.composio.dev/composio/server/<UUID>/mcp`) is used by the client applications to connect to the server.- The URL accepts three optional query parameters:--| Query param | Purpose |-|-------------|---------|-| `user_id` | Bind the session to a user identifier from your app. |-| `connected_account_id` | Pin the session to a specific Composio `connectedAccount` (skip account selection). |-| `include_composio_helper_actions=true` | Inject helper tools so the agent can walk the user through authentication when needed. |-- </Step>-</Steps>--<Tip>- SSE support will be deprecated soon. To use the latest protocol, if you are using `/sse` or the `transport=sse` query parameter, change your endpoint to use `/mcp` and remove the transport query parameter.-</Tip>--### Configuring authentication-You or your users need to authenticate against an app to use it's MCP server through Composio!-This can be done in two ways:--* Authenticate users upfront via the Composio SDK/API. Follow [custom auth configs](/docs/custom-auth-configs) to learn how to connect users. This is recommended for most use cases-* Let the agent authenticate users on demand. Passing `include_composio_helper_actions=true` in the URL will include Composio's helper actions and the agent will guide the user through auth on demand.+ });++ return {+ server: gmailServer,+ needsAuth: false,+ urls: serverUrls+ };+}++// Usage+const result = await setupGmailMCP("[email protected]");++if (result.needsAuth) {+ console.log(`Please authenticate: ${result.authUrl}`);+} else {+ console.log("Ready to use:", result.urls);+}+```++## Error Handling++```typescript+try {+ const mcpServer = await composio.mcp.create({+ name: "Test Server",+ serverConfig: [+ {+ authConfigId: "invalid_config",+ allowedTools: ["INVALID_TOOL"]+ }+ ],+ options: {+ isChatAuth: true+ }+ });+} catch (error) {+ if (error instanceof ValidationError) {+ console.error("Configuration error:", error.message);+ console.error("Details:", error.meta);+ } else {+ console.error("Unexpected error:", error);+ }+}+```++## Best Practices++1. **Use descriptive server names** - Makes management and debugging easier+2. **Check connection status first** - Always verify authentication before generating URLs+3. **Handle authentication gracefully** - Provide clear instructions and error messages+4. **Limit tools appropriately** - Only include tools your application actually needs+5. **Cache server configurations** - Reuse existing servers when possible+6. **Monitor connection health** - Regularly check and refresh user connections+7. **Use the convenience methods** - The `getServer` method on create responses simplifies workflows++## Next Steps++- **[Developer Guide](/docs/mcp-developers)** - Detailed implementation guide+- **[Provider Examples](/docs/mcp-providers)** - Framework-specific implementations+- **[Partner Program](/docs/mcp-partner-api)** - Enterprise integration options+- **[API Reference](/api-reference/mcp)** - Complete API documentationdiff --git a/fern/pages/src/mcp/overview.mdx b/fern/pages/src/mcp/overview.mdxindex 1903c0e28..5131afc6f 100644--- a/fern/pages/src/mcp/overview.mdx+++ b/fern/pages/src/mcp/overview.mdx@@ -1,29 +1,131 @@---title: Composio MCP Servers-subtitle: "Guide to working with Composio MCP servers"+subtitle: "Transform any app into an MCP server with powerful tools and seamless authentication"image: "https://og.composio.dev/api/og?title=Composio%20MCP%20Servers" # image for socials-keywords: ""+keywords: "MCP, Model Context Protocol, AI tools, authentication, SDK"hide-nav-links: true---+[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open protocol that standardizes how LLM-powered applications provide _tools_ and relevant context to the underlying models.-The protocol follows a client server model, where the MCP server provides the tools and context to the MCP client.+The protocol follows a client-server model, where the MCP server provides the tools and context to the MCP client.-All [tools](/tools) in Composio are also available through MCP servers.+**Composio MCP Servers** make all [Composio tools](/tools) available through this standardized protocol, enabling seamless integration with any MCP-compatible client.-<Tip>-Interested in embedding Composio MCP servers into your MCP clients or applications? Reach out on [email](mailto:[email protected]) to get started!-</Tip>+## ✨ Key Features++Our MCP SDK features an intuitive, powerful, and developer-friendly API:++- **⚡ Streamlined Authentication** - Simplified user auth flows with better error handling+- **📊 Real-time Connection Monitoring** - Check user authentication status before using servers+- **🛠 Enhanced Tool Management** - Fine-grained control over which tools are available+- **Tool Limiting** - Restrict which tools are available per user or context+- **TypeScript Support** - Full type safety and autocomplete, python support to come soon.+++## 🚀 Getting Started++Choose your path based on your role:++### For End Users+If you are an individual looking to use composio mcp servers directly for yourself, this is all you have todo.++1. Visit [mcp.composio.dev](https://mcp.composio.dev)+2. Click on any app that you want the MCP server for.+3. Use with Claude Desktop, Cursor, or any MCP client-## Getting Started-Composio MCP servers can be used in two ways:+### For Developers+If you are looking to build on top of composio MCP servers, have granual control over MCP servers and manage it seperately for each of your users - you can simply follow the below guide.-**1. For end users:**- Connect your accounts using our hosted MCP servers at [mcp.composio.dev](https://mcp.composio.dev)+<Steps>+ <Step title="Install the SDK">+ ```bash+ npm install @composio/core+ ```+ </Step>+ <Step title="Create your first server">+ ```typescript+ import { Composio } from '@composio/core';-**2. For developers:**- You can enable MCP servers for your users via the [Composio Admin Dashboard](https://app.composio.dev) or by integrating directly with our [MCP API reference](/api-reference/mcp).+ const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ });+ const mcpServer = await composio.mcp.create({+ name: "My Custom Server",+ serverConfig: [+ {+ authConfigId: "your_auth_config_id",+ allowedTools: ["GMAIL_FETCH_EMAILS"]+ }+ ],+ options: {+ isChatAuth: true+ }+ });+ ```+ </Step>+ <Step title="Generate user-specific URLs">+ ```typescript+ // Check if user is authenticated+ const status = await composio.mcp.getUserConnectionStatus({+ id: mcpServer.id,+ userId: "[email protected]"+ });-For detailed instructions on creating and configuring custom MCP servers, see the [developer guide](/docs/mcp-developers).+ if (status.connected) {+ const urls = await mcpServer.getServer({+ userId: "[email protected]"+ });+ console.log("Ready to use:", urls);+ }+ ```+ </Step>+</Steps>++## 🏗 Architecture Overview++```mermaid+graph TB+ A[Your Application] --> B[Composio SDK]+ B --> C[MCP Server]+ C --> D[Tools & Authentication]+ E[MCP Clients] --> C+ E --> F[Claude Desktop]+ E --> G[Cursor IDE]+ E --> H[Custom Clients]++ style C fill:#4762DA,color:#fff+ style B fill:#9EB6FF,color:#000+```++1. **Your Application** creates and manages MCP servers via the Composio SDK+2. **MCP Servers** expose your chosen tools with proper authentication+3. **MCP Clients** (Claude, Cursor, etc.) connect to servers and use tools+4. **Users** interact with tools through their preferred MCP client++## 📚 Documentation Structure++<Cards>+ <Card title="Developer Guide" href="/docs/mcp-developers" icon="code">+ Step-by-step guide to creating and managing MCP servers+ </Card>+ <Card title="Provider Examples" href="/docs/mcp-providers" icon="layers">+ Framework-specific implementations for Anthropic, OpenAI, Mastra, and more+ </Card>+ <Card title="Partner Program" href="/docs/mcp-partner-api" icon="handshake">+ Enterprise integration options and white-label solutions+ </Card>+</Cards>++## 🔗 Quick Links++- **[Complete API Guide](/docs/mcp/introduction)** - Learn all the methods and patterns+- **[Tool Catalog](/tools)** - Browse 1000+ available tools+- **[Dashboard](https://app.composio.dev)** - Manage servers and auth configs+- **[API Reference](/api-reference/mcp)** - Complete endpoint documentation++<Tip>+Need help getting started? Reach out on [Slack](https://composio.dev/slack) or [email](mailto:[email protected]) - our team is here to help!+</Tip>diff --git a/fern/pages/src/mcp/providers.mdx b/fern/pages/src/mcp/providers.mdxindex b45c4780c..bc3928629 100644--- a/fern/pages/src/mcp/providers.mdx+++ b/fern/pages/src/mcp/providers.mdx@@ -18,7 +18,7 @@ This guide introduces the primary MCP providers, each optimized for a popular ag## 1. Anthropic Provider-The **Anthropic Provider** is purpose-built for use with the Anthropic Claude API. It supports Model Context Protocol (MCP) tools via a lightweight client that exposes a `getServer` method for retrieving the appropriate Composio MCP Server URL, preconfigured for your user. This provider ensures seamless compatibility between Composio tools and Anthropic’s function calling APIs.+The **Anthropic Provider** is purpose-built for use with the Anthropic Claude API. It supports Model Context Protocol (MCP) tools via a lightweight client that exposes a `getServer` method for retrieving the appropriate Composio MCP Server URL, preconfigured for your user. This provider ensures seamless compatibility between Composio tools and Anthropic's function calling APIs.<CodeGroup><CodeGroupItem title="TypeScript">@@ -39,21 +39,35 @@ const composio = new Composio({provider: new AnthropicProvider({ cacheTools: true }),});-const mcpConfig = await composio.mcp.create(-"Gmail Readonly Server",-[- {- toolkit: "gmail",- allowedTools: ["GMAIL_FETCH_EMAILS"],- authConfigId: "<auth_config_id>"- },-],-{ useComposioManagedAuth: true }-);+// Create MCP server with the new API structure+const mcpConfig = await composio.mcp.create({+ name: "Gmail Readonly Server",+ serverConfig: [+ {+ authConfigId: "<auth_config_id>", // Your auth config ID+ allowedTools: ["GMAIL_FETCH_EMAILS"]+ }+ ],+ options: {+ isChatAuth: true+ }+});console.log(`✅ MCP server created: ${mcpConfig.id}`);console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);+// Check user connection status before proceeding+const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: mcpConfig.id,+ userId: "utkarsh-dixit"+});++if (!connectionStatus.connected) {+ console.log("❌ User needs to connect required accounts");+ // Handle authentication as needed+ return;+}+// Retrieve server instances for connected accountsconst serverInstances = await mcpConfig.getServer({userId: "utkarsh-dixit",@@ -122,22 +136,42 @@ const composio = new Composio({provider: new MastraProvider(),});-// Create an MCP server with the Gmail toolkit-const mcpConfig = await composio.mcp.create(-"Gmail Readonly Server",-[- {- toolkit: "GMAIL",- allowedTools: ["GMAIL_FETCH_EMAILS"],- authConfigId: "<auth_config_id>"- },-],-{ useComposioManagedAuth: true }-);+// Create an MCP server with the Gmail toolkit using new API structure+const mcpConfig = await composio.mcp.create({+ name: "Gmail Readonly Server",+ serverConfig: [+ {+ authConfigId: "<auth_config_id>", // Your auth config ID+ allowedTools: ["GMAIL_FETCH_EMAILS"]+ }+ ],+ options: {+ isChatAuth: true+ }+});console.log(`✅ MCP server created: ${mcpConfig.id}`);console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);+// Check user connection status+const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: mcpConfig.id,+ userId: "utkarsh-dixit"+});++console.log("Connection status:", connectionStatus.connected);++if (!connectionStatus.connected) {+ console.log("❌ User needs to authenticate with required services");+ // Handle authentication flow+ Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {+ if (!status.connected) {+ console.log(`Please connect ${toolkit}`);+ }+ });+ return;+}+// Retrieve server instance for connected accountsconst serverInstance = await mcpConfig.getServer({userId: "utkarsh-dixit"@@ -194,42 +228,91 @@ The **OpenAI SDK Provider** is designed for use with the OpenAI SDK and supports<CodeGroupItem title="TypeScript">```typescript+import { Composio } from '@composio/core';+import { OpenAIProvider } from '@composio/openai';+import OpenAI from 'openai';++const openai = new OpenAI({+ apiKey: process.env.OPENAI_API_KEY,+});+const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,- provider: new OpenAIResponsesProvider(),+ provider: new OpenAIProvider(),});-const mcpConfig = await composio.mcp.create(-"Gmail Readonly Server",-[- {- toolkit: "GMAIL",- allowedTools: ["GMAIL_FETCH_EMAILS"],- authConfigId: "<auth_config_id>"- },-],-{ useComposioManagedAuth: true }-);+// Create MCP server with new API structure+const mcpConfig = await composio.mcp.create({+ name: "Gmail Readonly Server",+ serverConfig: [+ {+ authConfigId: "<auth_config_id>", // Your auth config ID+ allowedTools: ["GMAIL_FETCH_EMAILS"]+ }+ ],+ options: {+ isChatAuth: true+ }+});console.log(`✅ MCP server created: ${mcpConfig.id}`);console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);+// Check if user has necessary connections+const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: mcpConfig.id,+ userId: "utkarsh-dixit"+});++if (!connectionStatus.connected) {+ console.log("❌ User authentication required");+ // Handle missing connections+ for (const [toolkit, status] of Object.entries(connectionStatus.connectedToolkits)) {+ if (!status.connected) {+ const authParams = await composio.mcp.getConnectionParams({+ id: mcpConfig.id,+ toolkit+ });++ const authRequest = await composio.mcp.authorize({+ id: mcpConfig.id,+ userId: "utkarsh-dixit",+ toolkit+ });++ if (authRequest.redirectUrl) {+ console.log(`Please authenticate with ${toolkit}: ${authRequest.redirectUrl}`);+ }+ }+ }+ return;+}+// Retrieve server URLs for connected accountsconst serverUrls = await mcpConfig.getServer({userId: "utkarsh-dixit",+ options: {+ limitTools: ["GMAIL_FETCH_EMAILS"] // Optional: limit to specific tools+ }});console.log("Server URLs for your MCP server:", serverUrls);-const completion = await openai.responses.create({-model: "gpt-4o-mini",-input:- "I've connected to Gmail and I want to fetch the latest email from my inbox and summarize it",-tools: serverUrls,+// Use with OpenAI (example with hypothetical OpenAI MCP integration)+const completion = await openai.chat.completions.create({+ model: "gpt-4o-mini",+ messages: [+ {+ role: "user",+ content: "I've connected to Gmail and I want to fetch the latest email from my inbox and summarize it"+ }+ ],+ // Note: This is a hypothetical integration - actual OpenAI MCP support may differ+ tools: serverUrls,});console.log("\n📬 Email Summary:");-console.log(completion.output_text);+console.log(completion.choices[0].message.content);console.log("\n✅ OpenAI MCP example completed successfully!");console.log("\n💡 Note: The MCP server URLs can also be used to connect from other MCP-compatible clients.");@@ -241,4 +324,37 @@ console.log(`📍 Server ID for future reference: ${mcpConfig.id}`);----By using Composio MCP Servers, you can quickly connect your agent framework to a wide range of external tools with minimal effort. This lets you streamline integration, reduce setup time, and focus more on building your AI agent.\ No newline at end of file+## Managing Existing Servers++You can also work with previously created MCP servers:++```typescript+// Find a server by name+const existingServer = await composio.mcp.getByName("Gmail Readonly Server");++// Check connection status for the existing server+const status = await composio.mcp.getUserConnectionStatus({+ id: existingServer.id,+ userId: "[email protected]"+});++// Generate URLs for the existing server+const urls = await composio.mcp.getServer({+ id: existingServer.id,+ userId: "[email protected]",+ options: {+ isChatAuth: true+ }+});+```++## Best Practices for Providers++1. **Always check connection status** before using MCP servers to ensure users are authenticated+2. **Handle authentication gracefully** by providing clear instructions and redirect URLs+3. **Use meaningful server names** to make management easier+4. **Limit tools appropriately** to only what your application needs+5. **Cache server configurations** when possible to reduce API calls+6. **Monitor connection health** and provide re-authentication flows when needed++By using Composio MCP Servers with these providers, you can quickly connect your agent framework to a wide range of external tools with minimal effort. This lets you streamline integration, reduce setup time, and focus more on building your AI agent.\ No newline at end of filediff --git a/ts/examples/openai/src/mcp.ts b/ts/examples/openai/src/mcp.tsindex 806451938..4f461fc3c 100644--- a/ts/examples/openai/src/mcp.ts+++ b/ts/examples/openai/src/mcp.ts@@ -9,7 +9,7 @@*/import { OpenAIResponsesProvider } from '@composio/openai';-import { Composio } from '@composio/core';+import { Composio, ConnectionStatus } from '@composio/core';import OpenAI from 'openai';import dotenv from 'dotenv';dotenv.config();@@ -29,39 +29,81 @@ const openai = new OpenAI({apiKey: process.env.OPENAI_API_KEY,});-// Create an MCP server with Gmail toolkit-const mcpConfig = await composio.mcp.create(- "gmail-mcp-openai-" + Date.now(),- [- {- toolkit: "gmail",- authConfigId: "<auth_config_id>", // Replace with your auth config ID- allowedTools: [- "GMAIL_FETCH_EMAILS"- ]+const MCP_SERVER_NAME = "gmail-readonly-server";+const USER_ID = "utkarsah";++// Check if MCP server with name already exists+let existingServer;+try {+ existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);+ console.log(`✅ Found existing MCP server: ${existingServer.id}`);+} catch (error) {+ // Server doesn't exist, create a new one+ console.log(`📝 Creating new MCP server: ${MCP_SERVER_NAME}`);++ const mcpConfig = await composio.mcp.create({+ name: MCP_SERVER_NAME,+ serverConfig: [+ {+ authConfigId: "ac_MbbEVd0i1TBG", // Replace with your auth config ID+ allowedTools: [+ "GMAIL_FETCH_EMAILS"+ ]+ }+ ],+ options: {+ // @TODO: Need better name for this+ isChatAuth: true}- ],- { useComposioManagedAuth: true }-);+ });++ // Get the newly created server details+ existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);+ console.log(`✅ MCP server created: ${existingServer.id}`);+}-console.log(`✅ MCP server created: ${mcpConfig.id}`);-console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(', ')}`);+console.log("Server details:", existingServer);-// Get server URLs with connected accounts (using convenience method)-const serverUrls = await mcpConfig.getServer({- connectedAccountIds: {- "gmail": "<connected_account_id>" // Replace with your connected account ID- }+const connectionStatus = await composio.mcp.getUserConnectionStatus({+ id: existingServer.id,+ userId: USER_ID,});-// Alternative: You can also use the standalone method to get URLs later-// const serverUrls = await composio.mcp.getServer(mcpConfig.id, {-// connectedAccountIds: {-// "gmail": "<connected_account_id>"-// }+console.log("Connection status:", connectionStatus);+const toolkits = connectionStatus.connectedToolkits;+for (let toolkit of Object.values(toolkits)) {+ if(toolkit.type === ConnectionStatus.DISCONNECTED) {+ const requiredParams = await composio.mcp.getConnectionParams({id: existingServer.id, toolkit: toolkit.toolkit});+ console.log("Required params:", requiredParams);+ const connectionStatus = await composio.mcp.authorize({id: existingServer.id, userId: USER_ID, toolkit: toolkit.toolkit});+ console.log("Connection status:", connectionStatus);+if (connectionStatus.redirectUrl) {+ console.log(`Please complete the authentication by visiting the following URL: ${connectionStatus.redirectUrl}`);+ console.log("Press 'Enter' once you have completed the authentication.");+ await new Promise(resolve => process.stdin.once('data', resolve));+}+}+}++// console.log(`✅ MCP server created: ${mcpConfig.id}`);+// console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(', ')}`);++// // Get server URLs with user ID (using convenience method)+// const serverUrls = await mcpConfig.getServer({+// userId: "utkarsh" // Replace with your user ID// });-console.log("Server URLs for connected accounts:", serverUrls);+// Alternative: You can also use the standalone method to get URLs later+const serverUrls = await composio.mcp.getServer({+ id: existingServer.id,+ userId: USER_ID,+ options: {+ limitTools: ["GMAIL_FETCH_EMAILS"],+ isChatAuth: true+ }+});++// console.log("Server URLs for user:", serverUrls);// Function to fetch and summarize emailsasync function fetchAndSummarizeEmails() {@@ -87,4 +129,4 @@ await fetchAndSummarizeEmails();console.log('\n✅ OpenAI MCP Example completed successfully!');console.log('\n💡 Note: The MCP server URLs can be used to connect from other MCP-compatible clients');-console.log(`📍 Server ID for future reference: ${mcpConfig.id}`);+console.log(`📍 Server ID for future reference: ${existingServer.id}`);diff --git a/ts/packages/core/src/models/MCP.ts b/ts/packages/core/src/models/MCP.tsindex 50b1cdf59..3472ae05d 100644--- a/ts/packages/core/src/models/MCP.ts+++ b/ts/packages/core/src/models/MCP.ts@@ -31,6 +31,9 @@ import {GenerateURLResponse,GenerateURLParamsSchema,GenerateURLParams,+ McpToolkitConnectionStatus,+ McpUserConnectionStatus,+ ConnectionStatus,} from '../types/mcp.types';import {CustomCreateResponse as CustomCreateResponseRaw,@@ -46,6 +49,9 @@ import {transformMcpUpdateResponse,transformMcpGenerateUrlResponse,} from '../utils/transformers/mcp';+import { Toolkits } from './Toolkits';+import { ToolkitAuthFieldsResponse } from '../types/toolkit.types';+import { ConnectionRequest } from '../types/connectionRequest.types';/*** MCP (Model Control Protocol) class@@ -54,10 +60,12 @@ import {export class MCP<T = McpServerGetResponse> {private client: ComposioClient;private provider?: BaseComposioProvider<unknown, unknown, unknown>;+ private toolkits: Toolkits;constructor(client: ComposioClient, provider?: BaseComposioProvider<unknown, unknown, unknown>) {this.client = client;this.provider = provider;+ this.toolkits = new Toolkits(client);telemetry.instrument(this);}@@ -90,55 +98,87 @@ export class MCP<T = McpServerGetResponse> {/*** Create a new MCP server- * @param {string} name - Unique name for the MCP server- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations- * @param {MCPAuthOptions} [authOptions] - Authentication configuration options+ * @param {Object} params - Parameters for creating the MCP server+ * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools+ * @param {Object} params.options - Server creation options+ * @param {string} params.options.name - Unique name for the MCP server+ * @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.mcp.create(- * "personal-mcp-server",- * [+ * const server = await composio.mcp.create({+ * serverConfig: [* {- * toolkit: "GMAIL",- * authConfigId: "ac_sdhkjfhjksdk",- * allowedTools: ["GMAIL_FETCH_EMAILS"],- * },+ * authConfigId: "ac_xyz",+ * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]+ * }* ],- * { useComposioManagedAuth: true },- * );- *- * // Option 1: Use convenience method on response- * const urls = await server.getServer({- * connectedAccountIds: { gmail: "account_id" }+ * options: {+ * name: "personal-mcp-server",+ * isChatAuth: true+ * }* });*- * // Option 2: Use standalone method later- * const urlsLater = await composio.mcp.getServer(server.id, {- * connectedAccountIds: { gmail: "account_id" }+ * // Use convenience method on response+ * const urls = await server.getServer({+ * userId: "user123"* });* ```*/- async create(- name: string,- toolkitConfigs: MCPToolkitConfig[],- authOptions?: MCPAuthOptions- ): Promise<McpServerCreateResponse<T>> {+ async create({+ name,+ serverConfig,+ options,+ }: {+ name: string;+ serverConfig: Array<{+ authConfigId: string;+ allowedTools: string[];+ }>;+ options: {+ isChatAuth?: boolean;+ };+ }): Promise<McpServerCreateResponse<T>> {// Validate inputs using Zod schemas- this.validateInputs(toolkitConfigs, authOptions);+ if (!serverConfig || serverConfig.length === 0) {+ throw new ValidationError('At least one auth config is required', {});+ }- const toolkits = toolkitConfigs.map(config => config.toolkit);+ if (!name) {+ throw new ValidationError('Server name is required', {});+ }++ // Check if server with this name already exists+ try {+ await this.getByName(name);+ // If we reach here, server exists+ throw new ValidationError('MCP server with this name already exists', {+ meta: { serverName: name },+ });+ } catch (error) {+ // If error is not about server not found, re-throw it+ if (error instanceof ValidationError && !error.message.includes('not found')) {+ throw error;+ }+ // Server doesn't exist, we can proceed with creation+ }++ // Get toolkits from auth configs+ const authConfigDetails = await Promise.all(+ serverConfig.map(config => this.client.authConfigs.retrieve(config.authConfigId))+ );+ const toolkits = authConfigDetails.map(config => config.toolkit.slug);// Create a custom MCP server with the toolkit configurationslet mcpServerCreatedResponse: CustomCreateResponseRaw;try {mcpServerCreatedResponse = await this.client.mcp.custom.create({- name,+ name: name,toolkits: toolkits,- custom_tools: toolkitConfigs.flatMap(config => config.allowedTools),- managed_auth_via_composio: authOptions?.useComposioManagedAuth || false,- auth_config_ids: toolkitConfigs.map(config => config.authConfigId),+ custom_tools: serverConfig.flatMap(config => config.allowedTools),+ managed_auth_via_composio: options.isChatAuth || false,+ auth_config_ids: serverConfig.map(config => config.authConfigId),});} catch (error) {throw new ValidationError('Failed to create MCP server', {@@ -164,70 +204,261 @@ export class MCP<T = McpServerGetResponse> {toolkits,getServer: async (params: MCPGetServerParams): Promise<T> => {// Delegate to the standalone getServer method- return this.getServer(camelCaseResponse.id, params, authOptions);+ return this.getServer({+ id: camelCaseResponse.id,+ userId: params.userId || Object.keys(params.connectedAccountIds || {})[0] || '',+ options: {+ isChatAuth: options.isChatAuth,+ },+ });},} as McpServerCreateResponse<T>;}+ /**+ * Get the connection status of a user for an MCP server+ *+ * Checks whether a user has the necessary connected accounts to use all toolkits+ * configured in the specified MCP server. Returns both overall connection status+ * and individual status for each toolkit.+ *+ * @param {Object} params - Parameters for checking connection status+ * @param {string} params.id - The UUID of the MCP server to check+ * @param {string} params.userId - The ID of the user to check connection status for+ * @returns {Promise<McpUserConnectionStatus>} Complete connection status including:+ * - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)+ * - `connected`: Boolean indicating if user can use the MCP server+ * - `connectedToolkits`: Record mapping each toolkit name to its individual connection status+ *+ * @throws {ValidationError} When MCP server has no toolkits configured+ * @throws {ValidationError} When MCP server retrieval fails+ *+ * @example+ * ```typescript+ * // Check if user can access an MCP server with Gmail and Slack toolkits+ * const connectionStatus = await composio.mcp.getUserConnectionStatus({+ * id: 'mcp-server-uuid',+ * userId: 'user123'+ * });+ *+ * if (connectionStatus.connected) {+ * console.log('User can access all required toolkits');+ * // connectionStatus.type === ConnectionStatus.CONNECTED+ * } else {+ * console.log('User is missing some toolkit connections');+ * // Check individual toolkit statuses+ * Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {+ * if (!status.connected) {+ * console.log(`Missing connection for toolkit: ${toolkit}`);+ * }+ * });+ * }+ * ```+ *+ * @example+ * ```typescript+ * // Example response when user has Gmail connected but missing Slack+ * {+ * type: ConnectionStatus.DISCONNECTED,+ * connected: false,+ * connectedToolkits: {+ * GMAIL: {+ * type: ConnectionStatus.CONNECTED,+ * connected: true,+ * toolkit: 'GMAIL',+ * connectedAccountId: 'conn_gmail_123'+ * },+ * SLACK: {+ * type: ConnectionStatus.DISCONNECTED,+ * connected: false,+ * toolkit: 'SLACK'+ * }+ * }+ * }+ * ```+ */+ async getUserConnectionStatus({+ id,+ userId,+ }: {+ id: string;+ userId: string;+ }): Promise<McpUserConnectionStatus> {+ const serverDetails = await this.get(id);++ if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) {+ throw new ValidationError('MCP server has no toolkits configured', {+ meta: { serverId: id },+ });+ }++ // @TODO(utkarsh-dixit): Add auth_config_ids support here+ const connectedAccounts = await this.client.connectedAccounts.list({+ user_ids: [userId],+ toolkit_slugs: serverDetails.toolkits.map(toolkit => toolkit.toLowerCase()),+ statuses: ['ACTIVE'],+ });++ const connectedAccountsByToolkit = new Map<string, string>();+ connectedAccounts.items?.forEach(account => {+ connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);+ });++ const connectedToolkits: Record<string, McpToolkitConnectionStatus> = {};+ let allToolkitsConnected = true;++ for (const toolkit of serverDetails.toolkits) {+ const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());++ if (connectedAccountId) {+ connectedToolkits[toolkit] = {+ type: ConnectionStatus.CONNECTED,+ connected: true,+ toolkit,+ connectedAccountId,+ };+ } else {+ connectedToolkits[toolkit] = {+ type: ConnectionStatus.DISCONNECTED,+ connected: false,+ toolkit,+ };+ allToolkitsConnected = false;+ }+ }++ if (allToolkitsConnected) {+ return {+ type: ConnectionStatus.CONNECTED,+ connected: true,+ connectedToolkits,+ };+ } else {+ return {+ type: ConnectionStatus.DISCONNECTED,+ connected: false,+ connectedToolkits,+ };+ }+ }++ async getConnectionParams({+ id,+ toolkit,+ }: {+ id: string;+ toolkit: string;+ }): Promise<ToolkitAuthFieldsResponse> {+ const mcpServerDetails = await this.get(id);+ const authConfigs = mcpServerDetails.authConfigIds+ ? await Promise.all(+ mcpServerDetails.authConfigIds.map(id => this.client.authConfigs.retrieve(id))+ )+ : [];++ const authConfig = authConfigs.find(config => config.toolkit.slug === toolkit);+ if (!authConfig) {+ throw new ValidationError('Auth config not found', {+ meta: { serverId: id, toolkit },+ });+ }++ const connectionParams = await this.toolkits.getConnectedAccountInitiationFields(+ toolkit,+ authConfig.auth_scheme!+ );+ return connectionParams;+ }++ async authorize({+ id,+ userId,+ toolkit,+ }: {+ id: string;+ userId: string;+ toolkit: string;+ }): Promise<ConnectionRequest> {+ const mcpServerDetails = await this.get(id);+ const authConfigId = mcpServerDetails.authConfigIds?.[0];+ return this.toolkits.authorize(userId, toolkit, authConfigId);+ }+/*** Get server URLs for an existing MCP server- * @param {string} id - Server UUID- * @param {MCPGetServerParams} params - Parameters for getting server URLs- * @param {MCPAuthOptions} [authOptions] - Authentication options (optional, will use server's default if not provided)+ * @param {Object} params - Parameters for getting server URLs+ * @param {string} params.id - Server UUID+ * @param {string} params.userId - User ID to get server URLs for+ * @param {Object} [params.options] - Additional options for server configuration+ * @param {string[]} [params.options.limitTools] - Subset of tools to limit (from MCP config)+ * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication* @returns {Promise<T>} Transformed server URLs in provider-specific format** @example* ```typescript- * // Get URLs for an existing server- * const urls = await composio.mcp.getServer("server-id", {- * connectedAccountIds: {- * gmail: "connected_account_id"+ * // Get URLs for an existing server with basic user ID+ * const urls = await composio.mcp.getServer({+ * id: "mcp_xyz",+ * userId: "[email protected]"+ * });+ *+ * // Get URLs with additional options+ * const urls = await composio.mcp.getServer({+ * id: "mcp_xyz",+ * userId: "[email protected]",+ * options: {+ * limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],+ * isChatAuth: true* }* });* ```*/- async getServer(- id: string,- params: MCPGetServerParams,- authOptions?: MCPAuthOptions- ): Promise<T> {+ async getServer({+ id,+ userId,+ options,+ }: {+ id: string;+ userId: string;+ options?: {+ limitTools?: string[];+ isChatAuth?: boolean;+ };+ }): Promise<T> {// Get server details firstconst serverDetails = await this.get(id);- // Validate params using Zod schema- const paramsResult = MCPGetServerParamsSchema.safeParse(params);- if (paramsResult.error) {- throw new ValidationError('Failed to parse get server parameters', {- cause: paramsResult.error,- });+ // Validate userId is provided+ if (!userId) {+ throw new ValidationError('User ID is required', {});}// Extract toolkits from server detailsconst toolkits = serverDetails.toolkits || [];- // If connected_account_ids is provided, verify toolkit names- if (paramsResult.data.connectedAccountIds) {- const providedToolkits = Object.keys(paramsResult.data.connectedAccountIds);- const invalidToolkits = providedToolkits.filter(toolkit => !toolkits.includes(toolkit));- if (invalidToolkits.length > 0) {- throw new ValidationError(- `Invalid toolkits provided: ${invalidToolkits.join(', ')}. Available toolkits are: ${toolkits.join(', ')}`,- {}- );- }- }+ const connectedAccountIds = (+ await Promise.all(+ toolkits.map(toolkit =>+ this.client.connectedAccounts+ .list({+ user_ids: [userId],+ toolkit_slugs: [toolkit],+ statuses: ['ACTIVE'],+ })+ .then(res => res.items?.[0]?.id)+ )+ )+ ).filter(Boolean);// Generate URL with error handlinglet data;try {data = await this.client.mcp.generate.url({- user_ids: paramsResult.data.userId ? [paramsResult.data.userId] : [],- connected_account_ids: paramsResult.data.connectedAccountIds- ? Object.values(paramsResult.data.connectedAccountIds)- : [],+ user_ids: [userId],+ connected_account_ids: connectedAccountIds,mcp_server_id: id,managed_auth_by_composio:- authOptions?.useComposioManagedAuth ?? serverDetails.managedAuthViaComposio ?? false,+ options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false,});} catch (error) {throw new ValidationError('Failed to generate MCP server URL', {@@ -250,13 +481,9 @@ export class MCP<T = McpServerGetResponse> {return this.wrapMcpServerResponse(camelCaseData,serverDetails.name,- paramsResult.data.connectedAccountIds- ? Object.values(paramsResult.data.connectedAccountIds)- : undefined,- paramsResult.data.userId ? [paramsResult.data.userId] : undefined,- paramsResult.data.connectedAccountIds- ? Object.keys(paramsResult.data.connectedAccountIds)- : undefined+ connectedAccountIds,+ [userId],+ toolkits);}@@ -299,8 +526,8 @@ export class MCP<T = McpServerGetResponse> {listResponse = await this.client.mcp.list({page_no: options.page || 1,limit: options.limit || 10,- toolkits: options?.toolkits?.join(',') || '',- auth_config_ids: options?.authConfigs?.join(',') || '',+ toolkits: options?.toolkits?.join(',') || undefined,+ auth_config_ids: options?.authConfigs?.join(',') || undefined,name: options?.name,});} catch (error) {@@ -566,4 +793,54 @@ export class MCP<T = McpServerGetResponse> {name: serverName,} as T;}++ /**+ * Get details of a specific MCP server by name+ * @param {string} name - Server name+ * @returns {Promise<McpRetrieveResponse>} Server details+ * @throws {ValidationError} If no server found with the given name+ * @throws {ValidationError} If multiple servers found with the same name+ *+ * @example+ * ```typescript+ * const serverDetails = await composio.mcp.getByName('my-gmail-server');+ * ```+ */+ async getByName(name: string): Promise<McpRetrieveResponse> {+ if (!name) {+ throw new ValidationError('Server name is required', {});+ }++ // List MCP servers filtered by name+ let listResponse;+ try {+ listResponse = await this.client.mcp.list({+ name: name,+ limit: 10,+ });+ } catch (error) {+ throw new ValidationError('Failed to search MCP servers by name', {+ cause: error,+ });+ }++ // Validate the list response+ const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);+ if (listResponseResult.error) {+ throw new ValidationError('Failed to parse MCP server list response', {+ cause: listResponseResult.error,+ });+ }++ const servers = listResponse.items || [];++ if (servers.length === 0) {+ throw new ValidationError(`MCP server with name '${name}' not found`, {+ meta: { serverName: name },+ });+ }++ // Get the full server details using the server ID+ return this.get(servers[0].id);+ }}diff --git a/ts/packages/core/src/models/Toolkits.ts b/ts/packages/core/src/models/Toolkits.tsindex 31d5574f5..dbfa7ccc4 100644--- a/ts/packages/core/src/models/Toolkits.ts+++ b/ts/packages/core/src/models/Toolkits.ts@@ -374,15 +374,22 @@ export class Toolkits {* const connectionRequest = await composio.toolkits.authorize(userId, 'github');* ```*/- async authorize(userId: string, toolkitSlug: string): Promise<ConnectionRequest> {+ async authorize(+ userId: string,+ toolkitSlug: string,+ authConfigId?: string+ ): Promise<ConnectionRequest> {const toolkit = await this.getToolkitBySlug(toolkitSlug);const composioAuthConfig = new AuthConfigs(this.client);- let authConfigIdToUse: string;- const authConfig = await composioAuthConfig.list({- toolkit: toolkitSlug,- });- // pick the first auth config- authConfigIdToUse = authConfig.items[0]?.id;+ let authConfigIdToUse: string | undefined = authConfigId;++ if (!authConfigIdToUse) {+ const authConfig = await composioAuthConfig.list({+ toolkit: toolkitSlug,+ });+ // pick the first auth config if none is passed+ authConfigIdToUse = authConfig.items[0]?.id;+ }// if no auth config is found, create one for the toolkitif (!authConfigIdToUse) {diff --git a/ts/packages/core/src/types/mcp.types.ts b/ts/packages/core/src/types/mcp.types.tsindex 05c90c0bc..d64fbb573 100644--- a/ts/packages/core/src/types/mcp.types.ts+++ b/ts/packages/core/src/types/mcp.types.ts@@ -202,6 +202,36 @@ export type McpServerCreateResponse<T> = (McpCreateResponseRaw | CustomCreateResgetServer: (params: MCPGetServerParams) => Promise<T>;};+export enum ConnectionStatus {+ CONNECTED = 'CONNECTED',+ DISCONNECTED = 'DISCONNECTED',+}++export type McpToolkitConnectionStatus =+ | {+ type: ConnectionStatus.CONNECTED;+ connected: true;+ toolkit: string;+ connectedAccountId: string;+ }+ | {+ type: ConnectionStatus.DISCONNECTED;+ connected: false;+ toolkit: string;+ };++export type McpUserConnectionStatus =+ | {+ type: ConnectionStatus.CONNECTED;+ connected: true;+ connectedToolkits: Record<string, McpToolkitConnectionStatus>;+ }+ | {+ type: ConnectionStatus.DISCONNECTED;+ connected: false;+ connectedToolkits: Record<string, McpToolkitConnectionStatus>;+ };+// CamelCase create response schemaexport const CustomCreateResponseSchema = z.object({id: z.string().min(1, 'Server ID cannot be empty'),@@ -263,6 +293,7 @@ export const McpRetrieveResponseSchema = z.object({toolkits: z.array(z.string()).optional(),tools: z.array(z.string()).optional(),managedAuthViaComposio: z.boolean().optional(),+ authConfigIds: z.array(z.string()).optional(),});// Snake_case retrieve response schema (for API)diff --git a/ts/packages/core/src/utils/transformers/mcp.ts b/ts/packages/core/src/utils/transformers/mcp.tsindex c01570928..6ba40e0e0 100644--- a/ts/packages/core/src/utils/transformers/mcp.ts+++ b/ts/packages/core/src/utils/transformers/mcp.ts@@ -86,6 +86,7 @@ export function transformMcpRetrieveResponse(toolkits: response.toolkits,tools: (response as unknown as Record<string, unknown>).tools,managedAuthViaComposio: response.managed_auth_via_composio,+ authConfigIds: response.auth_config_ids,});if (!result.success) {diff --git a/ts/packages/core/test/models/mcp.test.ts b/ts/packages/core/test/models/mcp.test.tsindex faede3bad..9b6b763ec 100644--- a/ts/packages/core/test/models/mcp.test.ts+++ b/ts/packages/core/test/models/mcp.test.ts@@ -100,6 +100,15 @@ const createMockClient = () => ({delete: vi.fn(),update: vi.fn(),},+ authConfigs: {+ retrieve: vi.fn(),+ },+ connectedAccounts: {+ list: vi.fn(),+ },+ toolkits: {+ retrieve: vi.fn(),+ },});// Mock response data@@ -207,19 +216,31 @@ describe('MCP', () => {});describe('create', () => {- const toolkitConfigs = [+ const serverConfig = [{- toolkit: 'gmail',authConfigId: 'ac_gmail123',allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],},];+ beforeEach(() => {+ // Mock authConfigs.retrieve to return toolkit information+ mockClient.authConfigs.retrieve.mockResolvedValue({+ id: 'ac_gmail123',+ toolkit: { slug: 'gmail' },+ auth_scheme: 'OAUTH2',+ });+ });+it('should create an MCP server successfully', async () => {mockClient.mcp.custom.create.mockResolvedValue(mockCreateResponse);- const result = await mcp.create('test-server', toolkitConfigs, {- useComposioManagedAuth: true,+ const result = await mcp.create({+ name: 'test-server',+ serverConfig,+ options: {+ isChatAuth: true,+ },});expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({@@ -240,53 +261,44 @@ describe('MCP', () => {expect(typeof result.getServer).toBe('function');});- it('should validate toolkit configurations', async () => {- const invalidConfigs = [- {- toolkit: '', // Empty toolkit- authConfigId: 'ac_123',- allowedTools: ['TOOL_1'],- },- ];-- await expect(mcp.create('test-server', invalidConfigs)).rejects.toThrow(ValidationError);- });-- it('should validate auth options', async () => {- const invalidAuthOptions = {- useComposioManagedAuth: 'true' as unknown as boolean, // Should be boolean- };+ it('should validate server configuration', async () => {+ const invalidConfigs: any[] = []; // Empty array- await expect(mcp.create('test-server', toolkitConfigs, invalidAuthOptions)).rejects.toThrow(- ValidationError- );+ await expect(+ mcp.create({+ name: 'test-server',+ serverConfig: invalidConfigs,+ options: {+ isChatAuth: true,+ },+ })+ ).rejects.toThrow('At least one auth config is required');});- it('should throw ValidationError when duplicate toolkits are provided', async () => {- const duplicateConfigs = [- {- toolkit: 'gmail',- authConfigId: 'ac_gmail123',- allowedTools: ['GMAIL_FETCH_EMAILS'],- },- {- toolkit: 'gmail',- authConfigId: 'ac_gmail456',- allowedTools: ['GMAIL_SEND_EMAIL'],- },- ];-- await expect(mcp.create('test-server', duplicateConfigs)).rejects.toThrow(- 'Duplicate toolkits are not allowed'- );+ it('should validate server name', async () => {+ await expect(+ mcp.create({+ name: '',+ serverConfig,+ options: {+ isChatAuth: true,+ },+ })+ ).rejects.toThrow('Server name is required');});it('should handle server creation errors', async () => {mockClient.mcp.custom.create.mockRejectedValue(new Error('Server creation failed'));- await expect(mcp.create('test-server', toolkitConfigs)).rejects.toThrow(- 'Failed to create MCP server'- );+ await expect(+ mcp.create({+ name: 'test-server',+ serverConfig,+ options: {+ isChatAuth: true,+ },+ })+ ).rejects.toThrow('Failed to create MCP server');});});@@ -303,20 +315,26 @@ describe('MCP', () => {tools: mockRetrieveResponse.tools,managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,});++ // Mock connectedAccounts.list+ mockClient.connectedAccounts.list.mockResolvedValue({+ items: [+ { id: 'account_123', toolkit: { slug: 'gmail' } },+ { id: 'account_456', toolkit: { slug: 'github' } },+ ],+ });});- it('should get server URLs with connected account IDs', async () => {+ it('should get server URLs with user ID', async () => {mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);- const result = await mcp.getServer('mcp_123', {- connectedAccountIds: {- gmail: 'account_123',- github: 'account_456',- },+ const result = await mcp.getServer({+ id: 'mcp_123',+ userId: 'user_123',});expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({- user_ids: [],+ user_ids: ['user_123'],connected_account_ids: ['account_123', 'account_456'],mcp_server_id: 'mcp_123',managed_auth_by_composio: true,@@ -325,44 +343,33 @@ describe('MCP', () => {expect(result).toBeDefined();});- it('should get server URLs with user ID', async () => {+ it('should get server URLs with options', async () => {mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);- const result = await mcp.getServer('mcp_123', {+ const result = await mcp.getServer({+ id: 'mcp_123',userId: 'user_123',+ options: {+ limitTools: ['GMAIL_FETCH_EMAILS'],+ isChatAuth: false,+ },});expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({user_ids: ['user_123'],- connected_account_ids: [],+ connected_account_ids: ['account_123', 'account_456'],mcp_server_id: 'mcp_123',- managed_auth_by_composio: true,+ managed_auth_by_composio: false,});});- it('should validate that either userId or connectedAccountIds is provided', async () => {- await expect(mcp.getServer('mcp_123', {})).rejects.toThrow(- 'Must provide either userId or connectedAccountIds, but not both'- );- });-- it('should validate that both userId and connectedAccountIds are not provided', async () => {+ it('should validate that userId is provided', async () => {await expect(- mcp.getServer('mcp_123', {- userId: 'user_123',- connectedAccountIds: { gmail: 'account_123' },+ mcp.getServer({+ id: 'mcp_123',+ userId: '',})- ).rejects.toThrow('Must provide either userId or connectedAccountIds, but not both');- });-- it('should validate toolkit names in connectedAccountIds', async () => {- await expect(- mcp.getServer('mcp_123', {- connectedAccountIds: {- slack: 'account_123', // Not in server's toolkits- },- })- ).rejects.toThrow('Invalid toolkits provided: slack');+ ).rejects.toThrow('User ID is required');});it('should use custom provider transformation', async () => {@@ -386,7 +393,8 @@ describe('MCP', () => {};mockClient.mcp.generate.url.mockResolvedValue(singleUserResponse);- const result = await mcpWithProvider.getServer('mcp_123', {+ const result = await mcpWithProvider.getServer({+ id: 'mcp_123',userId: 'user_123',});@@ -615,15 +623,20 @@ describe('MCP', () => {mockClient.mcp.retrieve.mockResolvedValue(mockRetrieveResponse);mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);- const toolkitConfigs = [+ const serverConfig = [{- toolkit: 'gmail',authConfigId: 'ac_gmail123',allowedTools: ['GMAIL_FETCH_EMAILS'],},];- const server = await mcp.create('test-server', toolkitConfigs);+ const server = await mcp.create({+ name: 'test-server',+ serverConfig,+ options: {+ isChatAuth: true,+ },+ });// Mock the internal get callvi.spyOn(mcp, 'get').mockResolvedValue({@@ -637,8 +650,13 @@ describe('MCP', () => {managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,});+ // Mock connectedAccounts.list for the convenience method+ mockClient.connectedAccounts.list.mockResolvedValue({+ items: [{ id: 'account_123', toolkit: { slug: 'gmail' } }],+ });+const urls = await server.getServer({- connectedAccountIds: { gmail: 'account_123' },+ userId: 'user123',});expect(urls).toBeDefined();@@ -647,32 +665,35 @@ describe('MCP', () => {});describe('validation error messages', () => {- it('should provide meaningful error messages for toolkit config validation', async () => {- const invalidConfigs = [- {- toolkit: 'gmail',- authConfigId: '', // Empty auth config ID- allowedTools: ['GMAIL_FETCH_EMAILS'],- },- ];-- await expect(mcp.create('test-server', invalidConfigs)).rejects.toThrow(- 'Auth config ID cannot be empty'- );+ it('should provide meaningful error messages for empty auth config', async () => {+ await expect(+ mcp.create({+ name: 'test-server',+ serverConfig: [],+ options: {+ isChatAuth: true,+ },+ })+ ).rejects.toThrow('At least one auth config is required');});- it('should provide meaningful error messages for empty allowed tools', async () => {- const invalidConfigs = [+ it('should provide meaningful error messages for empty server name', async () => {+ const serverConfig = [{- toolkit: 'gmail',authConfigId: 'ac_123',- allowedTools: [], // Empty tools array+ allowedTools: ['GMAIL_FETCH_EMAILS'],},];- await expect(mcp.create('test-server', invalidConfigs)).rejects.toThrow(- 'At least one tool must be specified'- );+ await expect(+ mcp.create({+ name: '',+ serverConfig,+ options: {+ isChatAuth: true,+ },+ })+ ).rejects.toThrow('Server name is required');});});});