Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 22:00 UTC
feat: update mcp flow in ts sdk
Utkarsh Dixit committed
Jul 5, 2025 at 19:30 UTC
2e46ed5614d3172b53bcc65726bbdb82dbb0aec2
10 files changed
+1487
-405
fern/pages/src/mcp/developers.mdx
+182
-56
@@ -6,84 +6,210 @@ keywords: ""
6
hide-nav-links: true
7
---
8
9
-
10
-## Introduction
11
-
9
Composio MCP lets you build custom MCP servers that your users can connect to and use to perform actions.
10
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.
11
12
## Creating MCP Servers and Onboarding End users
13
<Steps>
14
<Step title="Configure Authentication">
18
- - **Configure Toolkit permissions:**
19
- Select the specific scopes and permissions your integration requires for each connected application. This ensures your MCP server has the right level of access.
15
+ - **Create and Configure Toolkit permissions:**
16
+ - Select the specific scopes and permissions your integration requires for each connected application. This ensures your MCP server has the right level of access.
17
+ - Check this guide on what auth config is and how to configue it - [Auth Config setup guide](/docs/custom-auth-configs)
18
19
- **Customize the authentication experience (Optional):**
22
- Create a seamless, branded experience by providing your own OAuth credentials and customizing the consent screens.
23
-
24
- **Learn more:**
25
- - [Integration setup guide](/docs/custom-auth-configs) - Detailed walkthrough of configuring app integrations
26
- - [Custom auth configs](/docs/custom-auth-configs) - Instructions for customizing the authentication
20
+ - Create a seamless, branded experience by providing your own OAuth credentials and customizing the consent screens.
21
+ - Learn more here - [Custom auth configs](/docs/custom-auth-configs)
22
</Step>
23
<Step title="Create and configure an MCP server">
29
- Making the following request:
30
- ```bash
31
- curl -X POST https://backend.composio.dev/api/v3/mcp/servers \
32
- -H "x-api-key: <YOUR_API_KEY>" \
33
- -H "Content-Type: application/json" \
34
- -d '{
35
- "name": "Gmail MCP Server",
36
- "allowed_tools": [
37
- "GMAIL_FETCH_EMAIL",
38
- "GMAIL_CREATE_EMAIL_DRAFT",
39
- ],
40
- "auth_config_ids": ["ac_auth_12"]
41
- }'
42
- ```
43
- The response looks like:
24
+
25
+ ```typescript
26
+ import { Composio } from '@composio/core';
27
45
- ```json
46
- {
47
- "id": "5bc757cc-7a8e-431c-8616-7f57cbed2423",
48
- "name": "Gmail MCP Server"",
49
- "auth_config_ids": ["ac_auth_12"],
50
- "allowed_tools": [
51
- "GMAIL_FETCH_EMAIL",
52
- "GMAIL_CREATE_EMAIL_DRAFT",
28
+ const composio = new Composio({
29
+ apiKey: process.env.COMPOSIO_API_KEY,
30
+ });
31
+
32
+ // Create an MCP server with the new API structure
33
+ const mcpConfig = await composio.mcp.create({
34
+ name: "Gmail MCP Server",
35
+ serverConfig: [
36
+ {
37
+ authConfigId: "ac_auth_12", // Your auth config ID
38
+ allowedTools: [
39
+ "GMAIL_FETCH_EMAILS",
40
+ "GMAIL_CREATE_EMAIL_DRAFT",
41
+ "GMAIL_SEND_EMAIL"
42
+ ]
43
+ }
44
],
54
- "mcp_url": "https://mcp.composio.dev/composio/server/5bc757cc-7a8z-431c-8616-7f57cbed2421?transport=sse",
55
- "commands": {
56
- "cursor": "npx @composio/mcp@latest setup \"<mcp_url>\" --client cursor",
57
- "claude": "npx @composio/mcp@latest setup \"<mcp_url>\" --client claude",
58
- "windsurf": "npx @composio/mcp@latest setup \"<mcp_url>\" --client windsurf"
59
- },
60
- "created_at": "2025-05-18T22:15:25.926Z",
61
- "updated_at": "2025-05-18T22:15:25.926Z",
62
- "managed_auth_via_composio": false
63
- }
45
+ options: {
46
+ isChatAuth: true // Enable chat-based authentication
47
+ }
48
+ });
49
+
50
+ console.log(`✅ MCP server created: ${mcpConfig.id}`);
51
+ console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
52
+ ```
53
+ </Step>
54
+ <Step title="Generate server URLs for users">
55
+ **Using the SDK:**
56
+ ```typescript
57
+ // Get server URLs for a specific user
58
+ const serverUrls = await composio.mcp.getServer({
59
+ id: mcpConfig.id,
60
+ userId: "user123@example.com",
61
+ options: {
62
+ limitTools: ["GMAIL_FETCH_EMAILS"], // Optional: limit to specific tools
63
+ isChatAuth: true
64
+ }
65
+ });
66
+
67
+ console.log("Server URLs:", serverUrls);
68
+ ```
69
+
70
+ **Using the convenience method (from create response):**
71
+ ```typescript
72
+ // Use the convenience method on the created server
73
+ const serverUrls = await mcpConfig.getServer({
74
+ userId: "user123@example.com"
75
+ });
76
```
77
</Step>
78
<Step title="Client applications connect to the server">
67
- The resultant `mcp_url`; (`https://mcp.composio.dev/composio/server/<UUID>/mcp`) is used by the client applications to connect to the server.
68
- The URL accepts three optional query parameters:
79
+ 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.
80
70
-| Query param | Purpose |
71
-|-------------|---------|
72
-| `user_id` | Bind the session to a user identifier from your app. |
73
-| `connected_account_id` | Pin the session to a specific Composio `connectedAccount` (skip account selection). |
74
-| `include_composio_helper_actions=true` | Inject helper tools so the agent can walk the user through authentication when needed. |
81
+ **Example server URL structure:**
82
+ ```
83
+ https://mcp.composio.dev/composio/server/<UUID>/mcp?user_id=user123@example.com
84
+ ```
85
86
+ **Optional query parameters:**
87
+ | Query param | Purpose |
88
+ |-------------|---------|
89
+ | `user_id` | Bind the session to a user identifier from your app |
90
+ | `connected_account_id` | Pin the session to a specific Composio connected account |
91
+ | `include_composio_helper_actions=true` | Include helper tools for agent-guided authentication |
92
</Step>
93
</Steps>
94
95
+## Managing MCP Servers
96
+
97
+### Check User Connection Status
98
+
99
+Before using an MCP server, you can check if a user has the necessary connected accounts:
100
+
101
+```typescript
102
+// Check if a user has connected accounts for all required toolkits
103
+const connectionStatus = await composio.mcp.getUserConnectionStatus({
104
+ id: mcpConfig.id,
105
+ userId: "user123@example.com"
106
+});
107
+
108
+console.log("Overall connection status:", connectionStatus.connected);
109
+console.log("Individual toolkit status:", connectionStatus.connectedToolkits);
110
+
111
+// Handle missing connections
112
+if (!connectionStatus.connected) {
113
+ Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
114
+ if (!status.connected) {
115
+ console.log(`❌ ${toolkit} not connected`);
116
+ // Guide user through authentication
117
+ }
118
+ });
119
+}
120
+```
121
+
122
+### Find Servers by Name
123
+
124
+```typescript
125
+// Retrieve a server by its name
126
+const serverDetails = await composio.mcp.getByName("Gmail MCP Server");
127
+console.log("Server details:", serverDetails);
128
+```
129
+
130
+### List All Servers
131
+
132
+```typescript
133
+// List servers with filtering options
134
+const servers = await composio.mcp.list({
135
+ page: 1,
136
+ limit: 10,
137
+ toolkits: ["gmail", "slack"], // Filter by toolkits
138
+ name: "production" // Filter by name
139
+});
140
+
141
+console.log("Found servers:", servers.items);
142
+```
143
+
144
+### Update Server Configuration
145
+
146
+```typescript
147
+// Update an existing server (uses traditional API signature)
148
+const updatedServer = await composio.mcp.update(
149
+ "server-uuid",
150
+ "Updated Gmail Server",
151
+ [
152
+ {
153
+ toolkit: "gmail",
154
+ authConfigId: "ac_new_auth_config",
155
+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
156
+ }
157
+ ],
158
+ { useComposioManagedAuth: true }
159
+);
160
+```
161
+
162
+## Authentication Configuration
163
+
164
+### Option 1: Pre-authenticate Users (Recommended)
165
+
166
+Authenticate users upfront via the Composio SDK/API before they use the MCP server:
167
+
168
+```typescript
169
+// Check what authentication is needed
170
+const authParams = await composio.mcp.getConnectionParams({
171
+ id: mcpConfig.id,
172
+ toolkit: "gmail"
173
+});
174
+
175
+// Initiate authentication for a user
176
+const authRequest = await composio.mcp.authorize({
177
+ id: mcpConfig.id,
178
+ userId: "user123@example.com",
179
+ toolkit: "gmail"
180
+});
181
+
182
+if (authRequest.redirectUrl) {
183
+ console.log("Please complete authentication:", authRequest.redirectUrl);
184
+}
185
+```
186
+
187
+### Option 2: Agent-guided Authentication
188
+
189
+Let the agent authenticate users on-demand by including helper actions:
190
+
191
+```typescript
192
+const serverUrls = await composio.mcp.getServer({
193
+ id: mcpConfig.id,
194
+ userId: "user123@example.com"
195
+});
196
+
197
+// The server URLs will include helper actions that guide users through authentication
198
+```
199
+
200
<Tip>
80
- 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.
201
+Pre-authentication is recommended for production applications as it provides better user experience and more predictable behavior.
202
</Tip>
203
83
-### Configuring authentication
84
-You or your users need to authenticate against an app to use it's MCP server through Composio!
85
-This can be done in two ways:
204
+## Best Practices
205
+
206
+1. **Use meaningful server names** - This helps with organization and makes servers easier to find
207
+2. **Limit tools appropriately** - Only include the tools your users actually need
208
+3. **Check connection status** - Always verify user authentication before using server URLs
209
+4. **Handle authentication gracefully** - Provide clear instructions when users need to authenticate
210
+5. **Use the convenience methods** - The `getServer` method on create responses simplifies URL generation
211
87
-* 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
88
-* 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.
212
+<Warning>
213
+SSE support is deprecated. If you're using `/sse` endpoints or `transport=sse` query parameters, migrate to the standard `/mcp` endpoints.
214
+</Warning>
215
fern/pages/src/mcp/introduction.mdx
+443
-84
@@ -1,91 +1,450 @@
1
---
2
-title: Composio MCP Servers
3
-subtitle: "Guide to working with Composio MCP servers"
4
-image: "https://og.composio.dev/api/og?title=Composio%20MCP%20Servers" # image for socials
5
-keywords: ""
2
+title: Composio MCP Introduction
3
+subtitle: "Complete guide to using Composio MCP servers"
4
+image: "https://og.composio.dev/api/og?title=Composio%20MCP%20Introduction"
5
+keywords: "MCP, Model Context Protocol, Composio, SDK, TypeScript"
6
hide-nav-links: true
7
---
8
-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.
9
-
10
-To learn about the MCP clients, see the MCP documentation.
11
-To build with agents, one can customize the MCP server too.
12
-
13
-<Tip>
14
-Interested in embedding Composio MCP servers into your MCP clients or applications? Reach out via Slack or [Contact us](mailto:support@composio.dev) to get started!
15
-</Tip>
16
-
17
-## Creating Custom MCP Servers
18
-<Steps>
19
- <Step title="Configure Authentication">
20
- - **Configure app permissions:**
21
- Select the specific scopes and permissions your integration requires for each connected application. This ensures your MCP server has the right level of access.
22
-
23
- - **Customize the authentication experience (Optional):**
24
- Create a seamless, branded experience by providing your own OAuth credentials and customizing the consent screens.
25
-
26
- **Learn more:**
27
- - [Integration setup guide](/docs/custom-auth-configs) - Detailed walkthrough of configuring app integrations
28
- - [Custom auth configs](/docs/custom-auth-configs) - Instructions for customizing the authentication
29
- </Step>
30
- <Step title="Create and configure an MCP server">
31
- Making the following request:
32
- ```bash
33
- curl -X POST https://backend.composio.dev/api/v3/mcp/servers \
34
- -H "x-api-key: <YOUR_API_KEY>" \
35
- -H "Content-Type: application/json" \
36
- -d '{
37
- "name": "Gmail MCP Server",
38
- "allowed_tools": [
39
- "GMAIL_FETCH_EMAIL",
40
- "GMAIL_CREATE_EMAIL_DRAFT",
41
- ],
42
- "auth_config_ids": ["ac_auth_12"]
43
- }'
44
- ```
45
- The response looks like:
46
-
47
- ```json
8
+
9
+## What is Composio MCP?
10
+
11
+[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.
12
+
13
+## Key Features
14
+
15
+- **🔧 1000+ Tools**: Access to all Composio tools through MCP
16
+- **🔐 Managed Authentication**: Streamlined user authentication and account management
17
+- **🌍 Multi-Framework Support**: Works with Claude, Anthropic, OpenAI, Mastra, and more
18
+- **📊 Connection Monitoring**: Real-time status tracking for user connections
19
+- **⚡ Easy Setup**: Simple SDK with intuitive named object arguments
20
+- **🎯 Flexible Configuration**: Fine-grained control over tools and permissions
21
+
22
+## Quick Start
23
+
24
+### Installation
25
+
26
+```bash
27
+npm install @composio/core
28
+```
29
+
30
+### Basic Usage
31
+
32
+```typescript
33
+import { Composio } from '@composio/core';
34
+
35
+const composio = new Composio({
36
+ apiKey: process.env.COMPOSIO_API_KEY,
37
+});
38
+
39
+// Create an MCP server
40
+const mcpServer = await composio.mcp.create({
41
+ name: "My Gmail Server",
42
+ serverConfig: [
43
+ {
44
+ authConfigId: "ac_your_auth_config_id",
45
+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
46
+ }
47
+ ],
48
+ options: {
49
+ isChatAuth: true
50
+ }
51
+});
52
+
53
+// Get server URLs for a user
54
+const serverUrls = await mcpServer.getServer({
55
+ userId: "user@example.com"
56
+});
57
+
58
+console.log("MCP Server URLs:", serverUrls);
59
+```
60
+
61
+## Complete API Reference
62
+
63
+### Creating MCP Servers
64
+
65
+The `create` method uses named object arguments for clear, readable configuration:
66
+
67
+```typescript
68
+const mcpServer = await composio.mcp.create({
69
+ name: string, // Unique server name
70
+ serverConfig: Array<{ // Auth configurations
71
+ authConfigId: string, // Your auth config ID
72
+ allowedTools: string[] // List of tool names
73
+ }>,
74
+ options: {
75
+ isChatAuth?: boolean // Enable chat-based auth (default: false)
76
+ }
77
+});
78
+```
79
+
80
+**Complete Example:**
81
+
82
+```typescript
83
+const mcpServer = await composio.mcp.create({
84
+ name: "Multi-Service Productivity Server",
85
+ serverConfig: [
86
+ {
87
+ authConfigId: "ac_gmail_config",
88
+ allowedTools: [
89
+ "GMAIL_FETCH_EMAILS",
90
+ "GMAIL_SEND_EMAIL",
91
+ "GMAIL_CREATE_DRAFT"
92
+ ]
93
+ },
94
+ {
95
+ authConfigId: "ac_slack_config",
96
+ allowedTools: [
97
+ "SLACK_SEND_MESSAGE",
98
+ "SLACK_GET_CHANNELS"
99
+ ]
100
+ }
101
+ ],
102
+ options: {
103
+ isChatAuth: true
104
+ }
105
+});
106
+
107
+console.log(`✅ Server created: ${mcpServer.id}`);
108
+console.log(`📦 Toolkits: ${mcpServer.toolkits.join(", ")}`);
109
+```
110
+
111
+### Generating Server URLs
112
+
113
+The `getServer` method provides URLs for MCP clients to connect:
114
+
115
+```typescript
116
+const serverUrls = await composio.mcp.getServer({
117
+ id: string, // Server ID
118
+ userId: string, // User identifier
119
+ options?: {
120
+ limitTools?: string[], // Subset of tools to include
121
+ isChatAuth?: boolean // Override chat auth setting
122
+ }
123
+});
124
+```
125
+
126
+**Examples:**
127
+
128
+```typescript
129
+// Basic usage
130
+const basicUrls = await composio.mcp.getServer({
131
+ id: "mcp_server_id",
132
+ userId: "user123@example.com"
133
+});
134
+
135
+// With tool limitations
136
+const limitedUrls = await composio.mcp.getServer({
137
+ id: "mcp_server_id",
138
+ userId: "user123@example.com",
139
+ options: {
140
+ limitTools: ["GMAIL_FETCH_EMAILS"], // Only allow email fetching
141
+ isChatAuth: false
142
+ }
143
+});
144
+
145
+// Using convenience method (from create response)
146
+const convenientUrls = await mcpServer.getServer({
147
+ userId: "user123@example.com"
148
+});
149
+```
150
+
151
+### Checking User Connection Status
152
+
153
+Before using an MCP server, check if users have the required connected accounts:
154
+
155
+```typescript
156
+const connectionStatus = await composio.mcp.getUserConnectionStatus({
157
+ id: string, // Server ID
158
+ userId: string // User identifier
159
+});
160
+
161
+// Returns: McpUserConnectionStatus
162
+{
163
+ type: "CONNECTED" | "DISCONNECTED",
164
+ connected: boolean,
165
+ connectedToolkits: {
166
+ [toolkitName: string]: {
167
+ type: "CONNECTED" | "DISCONNECTED",
168
+ connected: boolean,
169
+ toolkit: string,
170
+ connectedAccountId?: string // Present if connected
171
+ }
172
+ }
173
+}
174
+```
175
+
176
+**Complete Example:**
177
+
178
+```typescript
179
+const status = await composio.mcp.getUserConnectionStatus({
180
+ id: mcpServer.id,
181
+ userId: "user123@example.com"
182
+});
183
+
184
+console.log(`Overall status: ${status.connected ? "✅ Ready" : "❌ Needs auth"}`);
185
+
186
+// Handle missing connections
187
+if (!status.connected) {
188
+ for (const [toolkit, toolkitStatus] of Object.entries(status.connectedToolkits)) {
189
+ if (!toolkitStatus.connected) {
190
+ console.log(`❌ ${toolkit} requires authentication`);
191
+
192
+ // Get authentication parameters
193
+ const authParams = await composio.mcp.getConnectionParams({
194
+ id: mcpServer.id,
195
+ toolkit
196
+ });
197
+
198
+ // Initiate authentication
199
+ const authRequest = await composio.mcp.authorize({
200
+ id: mcpServer.id,
201
+ userId: "user123@example.com",
202
+ toolkit
203
+ });
204
+
205
+ if (authRequest.redirectUrl) {
206
+ console.log(`🔗 Authenticate here: ${authRequest.redirectUrl}`);
207
+ }
208
+ } else {
209
+ console.log(`✅ ${toolkit} connected (${toolkitStatus.connectedAccountId})`);
210
+ }
211
+ }
212
+}
213
+```
214
+
215
+### Managing Existing Servers
216
+
217
+#### Find Servers by Name
218
+
219
+```typescript
220
+const server = await composio.mcp.getByName("My Gmail Server");
221
+console.log(`Found server: ${server.id}`);
222
+```
223
+
224
+#### List All Servers
225
+
226
+```typescript
227
+const servers = await composio.mcp.list({
228
+ page: 1,
229
+ limit: 10,
230
+ toolkits: ["gmail", "slack"], // Filter by toolkits
231
+ authConfigs: ["ac_123"], // Filter by auth configs
232
+ name: "production" // Filter by name pattern
233
+});
234
+
235
+console.log(`Found ${servers.items?.length} servers`);
236
+```
237
+
238
+#### Get Server Details
239
+
240
+```typescript
241
+const serverDetails = await composio.mcp.get("mcp_server_id");
242
+console.log("Server details:", serverDetails);
243
+```
244
+
245
+#### Update Server Configuration
246
+
247
+```typescript
248
+const updatedServer = await composio.mcp.update(
249
+ "mcp_server_id",
250
+ "Updated Server Name",
251
+ [
252
{
49
- "id": "5bc757cc-7a8e-431c-8616-7f57cbed2423",
50
- "name": "Gmail MCP Server"",
51
- "auth_config_ids": ["ac_auth_12"],
52
- "allowed_tools": [
53
- "GMAIL_FETCH_EMAIL",
54
- "GMAIL_CREATE_EMAIL_DRAFT",
253
+ toolkit: "gmail",
254
+ authConfigId: "ac_new_config",
255
+ allowedTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
256
+ }
257
+ ],
258
+ { useComposioManagedAuth: true }
259
+);
260
+```
261
+
262
+#### Delete Server
263
+
264
+```typescript
265
+const deleteResult = await composio.mcp.delete("mcp_server_id");
266
+console.log("Server deleted:", deleteResult.deleted);
267
+```
268
+
269
+## Authentication Workflows
270
+
271
+### Pre-Authentication (Recommended)
272
+
273
+Authenticate users before they use the MCP server:
274
+
275
+```typescript
276
+// 1. Check what's needed
277
+const authParams = await composio.mcp.getConnectionParams({
278
+ id: mcpServer.id,
279
+ toolkit: "gmail"
280
+});
281
+
282
+console.log("Required fields:", authParams.required_fields);
283
+
284
+// 2. Initiate authentication
285
+const authRequest = await composio.mcp.authorize({
286
+ id: mcpServer.id,
287
+ userId: "user@example.com",
288
+ toolkit: "gmail"
289
+});
290
+
291
+// 3. Direct user to authentication URL
292
+if (authRequest.redirectUrl) {
293
+ console.log("Please visit:", authRequest.redirectUrl);
294
+}
295
+
296
+// 4. Verify connection after user completes auth
297
+const finalStatus = await composio.mcp.getUserConnectionStatus({
298
+ id: mcpServer.id,
299
+ userId: "user@example.com"
300
+});
301
+
302
+if (finalStatus.connected) {
303
+ console.log("✅ All toolkits connected, ready to use!");
304
+}
305
+```
306
+
307
+### Agent-Guided Authentication
308
+
309
+Let the agent handle authentication on-demand:
310
+
311
+```typescript
312
+const serverUrls = await composio.mcp.getServer({
313
+ id: mcpServer.id,
314
+ userId: "user@example.com",
315
+ options: {
316
+ isChatAuth: true // Include helper actions for authentication
317
+ }
318
+});
319
+
320
+// The agent can now guide users through authentication as needed
321
+```
322
+
323
+## Real-World Example: Complete Gmail Integration
324
+
325
+```typescript
326
+import { Composio } from '@composio/core';
327
+
328
+const composio = new Composio({
329
+ apiKey: process.env.COMPOSIO_API_KEY,
330
+});
331
+
332
+async function setupGmailMCP(userId: string) {
333
+ // 1. Check if server already exists
334
+ let gmailServer;
335
+ try {
336
+ gmailServer = await composio.mcp.getByName("Production Gmail Server");
337
+ console.log("✅ Using existing server");
338
+ } catch (error) {
339
+ // 2. Create new server if it doesn't exist
340
+ console.log("📦 Creating new Gmail server...");
341
+ gmailServer = await composio.mcp.create({
342
+ name: "Production Gmail Server",
343
+ serverConfig: [
344
+ {
345
+ authConfigId: process.env.GMAIL_AUTH_CONFIG_ID!,
346
+ allowedTools: [
347
+ "GMAIL_FETCH_EMAILS",
348
+ "GMAIL_SEND_EMAIL",
349
+ "GMAIL_CREATE_DRAFT",
350
+ "GMAIL_SEARCH_EMAILS"
351
+ ]
352
+ }
353
],
56
- "mcp_url": "https://mcp.composio.dev/composio/server/5bc757cc-7a8z-431c-8616-7f57cbed2421?transport=sse",
57
- "commands": {
58
- "cursor": "npx @composio/mcp@latest setup \"<mcp_url>\" --client cursor",
59
- "claude": "npx @composio/mcp@latest setup \"<mcp_url>\" --client claude",
60
- "windsurf": "npx @composio/mcp@latest setup \"<mcp_url>\" --client windsurf"
61
- },
62
- "created_at": "2025-05-18T22:15:25.926Z",
63
- "updated_at": "2025-05-18T22:15:25.926Z",
64
- "managed_auth_via_composio": false
354
+ options: {
355
+ isChatAuth: true
356
+ }
357
+ });
358
+ }
359
+
360
+ // 3. Check user connection status
361
+ const connectionStatus = await composio.mcp.getUserConnectionStatus({
362
+ id: gmailServer.id,
363
+ userId
364
+ });
365
+
366
+ // 4. Handle authentication if needed
367
+ if (!connectionStatus.connected) {
368
+ console.log("🔐 User needs to authenticate with Gmail");
369
+
370
+ const authRequest = await composio.mcp.authorize({
371
+ id: gmailServer.id,
372
+ userId,
373
+ toolkit: "gmail"
374
+ });
375
+
376
+ return {
377
+ server: gmailServer,
378
+ needsAuth: true,
379
+ authUrl: authRequest.redirectUrl
380
+ };
381
+ }
382
+
383
+ // 5. Generate server URLs for MCP client
384
+ const serverUrls = await gmailServer.getServer({
385
+ userId,
386
+ options: {
387
+ limitTools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
388
}
66
- ```
67
- </Step>
68
- <Step title="Client applications connect to the server">
69
- The resultant `mcp_url`; (`https://mcp.composio.dev/composio/server/<UUID>/mcp`) is used by the client applications to connect to the server.
70
- The URL accepts three optional query parameters:
71
-
72
-| Query param | Purpose |
73
-|-------------|---------|
74
-| `user_id` | Bind the session to a user identifier from your app. |
75
-| `connected_account_id` | Pin the session to a specific Composio `connectedAccount` (skip account selection). |
76
-| `include_composio_helper_actions=true` | Inject helper tools so the agent can walk the user through authentication when needed. |
77
-
78
- </Step>
79
-</Steps>
80
-
81
-<Tip>
82
- 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.
83
-</Tip>
84
-
85
-### Configuring authentication
86
-You or your users need to authenticate against an app to use it's MCP server through Composio!
87
-This can be done in two ways:
88
-
89
-* 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
90
-* 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.
389
+ });
390
+
391
+ return {
392
+ server: gmailServer,
393
+ needsAuth: false,
394
+ urls: serverUrls
395
+ };
396
+}
397
+
398
+// Usage
399
+const result = await setupGmailMCP("user@example.com");
400
+
401
+if (result.needsAuth) {
402
+ console.log(`Please authenticate: ${result.authUrl}`);
403
+} else {
404
+ console.log("Ready to use:", result.urls);
405
+}
406
+```
407
+
408
+## Error Handling
409
+
410
+```typescript
411
+try {
412
+ const mcpServer = await composio.mcp.create({
413
+ name: "Test Server",
414
+ serverConfig: [
415
+ {
416
+ authConfigId: "invalid_config",
417
+ allowedTools: ["INVALID_TOOL"]
418
+ }
419
+ ],
420
+ options: {
421
+ isChatAuth: true
422
+ }
423
+ });
424
+} catch (error) {
425
+ if (error instanceof ValidationError) {
426
+ console.error("Configuration error:", error.message);
427
+ console.error("Details:", error.meta);
428
+ } else {
429
+ console.error("Unexpected error:", error);
430
+ }
431
+}
432
+```
433
+
434
+## Best Practices
435
+
436
+1. **Use descriptive server names** - Makes management and debugging easier
437
+2. **Check connection status first** - Always verify authentication before generating URLs
438
+3. **Handle authentication gracefully** - Provide clear instructions and error messages
439
+4. **Limit tools appropriately** - Only include tools your application actually needs
440
+5. **Cache server configurations** - Reuse existing servers when possible
441
+6. **Monitor connection health** - Regularly check and refresh user connections
442
+7. **Use the convenience methods** - The `getServer` method on create responses simplifies workflows
443
+
444
+## Next Steps
445
+
446
+- **[Developer Guide](/docs/mcp-developers)** - Detailed implementation guide
447
+- **[Provider Examples](/docs/mcp-providers)** - Framework-specific implementations
448
+- **[Partner Program](/docs/mcp-partner-api)** - Enterprise integration options
449
+- **[API Reference](/api-reference/mcp)** - Complete API documentation
450
fern/pages/src/mcp/overview.mdx
+116
-14
@@ -1,29 +1,131 @@
1
---
2
title: Composio MCP Servers
3
-subtitle: "Guide to working with Composio MCP servers"
3
+subtitle: "Transform any app into an MCP server with powerful tools and seamless authentication"
4
image: "https://og.composio.dev/api/og?title=Composio%20MCP%20Servers" # image for socials
5
-keywords: ""
5
+keywords: "MCP, Model Context Protocol, AI tools, authentication, SDK"
6
hide-nav-links: true
7
---
8
+
9
[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.
10
10
-The protocol follows a client server model, where the MCP server provides the tools and context to the MCP client.
11
+The protocol follows a client-server model, where the MCP server provides the tools and context to the MCP client.
12
12
-All [tools](/tools) in Composio are also available through MCP servers.
13
+**Composio MCP Servers** make all [Composio tools](/tools) available through this standardized protocol, enabling seamless integration with any MCP-compatible client.
14
14
-<Tip>
15
-Interested in embedding Composio MCP servers into your MCP clients or applications? Reach out on [email](mailto:support@composio.dev) to get started!
16
-</Tip>
15
+## ✨ Key Features
16
+
17
+Our MCP SDK features an intuitive, powerful, and developer-friendly API:
18
+
19
+- **⚡ Streamlined Authentication** - Simplified user auth flows with better error handling
20
+- **📊 Real-time Connection Monitoring** - Check user authentication status before using servers
21
+- **🛠 Enhanced Tool Management** - Fine-grained control over which tools are available
22
+- **Tool Limiting** - Restrict which tools are available per user or context
23
+- **TypeScript Support** - Full type safety and autocomplete, python support to come soon.
24
+
25
+
26
+## 🚀 Getting Started
27
+
28
+Choose your path based on your role:
29
+
30
+### For End Users
31
+If you are an individual looking to use composio mcp servers directly for yourself, this is all you have todo.
32
+
33
+1. Visit [mcp.composio.dev](https://mcp.composio.dev)
34
+2. Click on any app that you want the MCP server for.
35
+3. Use with Claude Desktop, Cursor, or any MCP client
36
18
-## Getting Started
19
-Composio MCP servers can be used in two ways:
37
+### For Developers
38
+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.
39
21
-**1. For end users:**
22
- Connect your accounts using our hosted MCP servers at [mcp.composio.dev](https://mcp.composio.dev)
40
+<Steps>
41
+ <Step title="Install the SDK">
42
+ ```bash
43
+ npm install @composio/core
44
+ ```
45
+ </Step>
46
+ <Step title="Create your first server">
47
+ ```typescript
48
+ import { Composio } from '@composio/core';
49
24
-**2. For developers:**
25
- 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).
50
+ const composio = new Composio({
51
+ apiKey: process.env.COMPOSIO_API_KEY,
52
+ });
53
54
+ const mcpServer = await composio.mcp.create({
55
+ name: "My Custom Server",
56
+ serverConfig: [
57
+ {
58
+ authConfigId: "your_auth_config_id",
59
+ allowedTools: ["GMAIL_FETCH_EMAILS"]
60
+ }
61
+ ],
62
+ options: {
63
+ isChatAuth: true
64
+ }
65
+ });
66
+ ```
67
+ </Step>
68
+ <Step title="Generate user-specific URLs">
69
+ ```typescript
70
+ // Check if user is authenticated
71
+ const status = await composio.mcp.getUserConnectionStatus({
72
+ id: mcpServer.id,
73
+ userId: "user@example.com"
74
+ });
75
28
-For detailed instructions on creating and configuring custom MCP servers, see the [developer guide](/docs/mcp-developers).
76
+ if (status.connected) {
77
+ const urls = await mcpServer.getServer({
78
+ userId: "user@example.com"
79
+ });
80
+ console.log("Ready to use:", urls);
81
+ }
82
+ ```
83
+ </Step>
84
+</Steps>
85
+
86
+## 🏗 Architecture Overview
87
+
88
+```mermaid
89
+graph TB
90
+ A[Your Application] --> B[Composio SDK]
91
+ B --> C[MCP Server]
92
+ C --> D[Tools & Authentication]
93
+ E[MCP Clients] --> C
94
+ E --> F[Claude Desktop]
95
+ E --> G[Cursor IDE]
96
+ E --> H[Custom Clients]
97
+
98
+ style C fill:#4762DA,color:#fff
99
+ style B fill:#9EB6FF,color:#000
100
+```
101
+
102
+1. **Your Application** creates and manages MCP servers via the Composio SDK
103
+2. **MCP Servers** expose your chosen tools with proper authentication
104
+3. **MCP Clients** (Claude, Cursor, etc.) connect to servers and use tools
105
+4. **Users** interact with tools through their preferred MCP client
106
+
107
+## 📚 Documentation Structure
108
+
109
+<Cards>
110
+ <Card title="Developer Guide" href="/docs/mcp-developers" icon="code">
111
+ Step-by-step guide to creating and managing MCP servers
112
+ </Card>
113
+ <Card title="Provider Examples" href="/docs/mcp-providers" icon="layers">
114
+ Framework-specific implementations for Anthropic, OpenAI, Mastra, and more
115
+ </Card>
116
+ <Card title="Partner Program" href="/docs/mcp-partner-api" icon="handshake">
117
+ Enterprise integration options and white-label solutions
118
+ </Card>
119
+</Cards>
120
+
121
+## 🔗 Quick Links
122
+
123
+- **[Complete API Guide](/docs/mcp/introduction)** - Learn all the methods and patterns
124
+- **[Tool Catalog](/tools)** - Browse 1000+ available tools
125
+- **[Dashboard](https://app.composio.dev)** - Manage servers and auth configs
126
+- **[API Reference](/api-reference/mcp)** - Complete endpoint documentation
127
+
128
+<Tip>
129
+Need help getting started? Reach out on [Slack](https://composio.dev/slack) or [email](mailto:support@composio.dev) - our team is here to help!
130
+</Tip>
131
fern/pages/src/mcp/providers.mdx
+159
-43
@@ -18,7 +18,7 @@ This guide introduces the primary MCP providers, each optimized for a popular ag
18
19
## 1. Anthropic Provider
20
21
-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.
21
+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.
22
23
<CodeGroup>
24
<CodeGroupItem title="TypeScript">
@@ -39,21 +39,35 @@ const composio = new Composio({
39
provider: new AnthropicProvider({ cacheTools: true }),
40
});
41
42
-const mcpConfig = await composio.mcp.create(
43
-"Gmail Readonly Server",
44
-[
45
- {
46
- toolkit: "gmail",
47
- allowedTools: ["GMAIL_FETCH_EMAILS"],
48
- authConfigId: "<auth_config_id>"
49
- },
50
-],
51
-{ useComposioManagedAuth: true }
52
-);
42
+// Create MCP server with the new API structure
43
+const mcpConfig = await composio.mcp.create({
44
+ name: "Gmail Readonly Server",
45
+ serverConfig: [
46
+ {
47
+ authConfigId: "<auth_config_id>", // Your auth config ID
48
+ allowedTools: ["GMAIL_FETCH_EMAILS"]
49
+ }
50
+ ],
51
+ options: {
52
+ isChatAuth: true
53
+ }
54
+});
55
56
console.log(`✅ MCP server created: ${mcpConfig.id}`);
57
console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
58
59
+// Check user connection status before proceeding
60
+const connectionStatus = await composio.mcp.getUserConnectionStatus({
61
+ id: mcpConfig.id,
62
+ userId: "utkarsh-dixit"
63
+});
64
+
65
+if (!connectionStatus.connected) {
66
+ console.log("❌ User needs to connect required accounts");
67
+ // Handle authentication as needed
68
+ return;
69
+}
70
+
71
// Retrieve server instances for connected accounts
72
const serverInstances = await mcpConfig.getServer({
73
userId: "utkarsh-dixit",
@@ -122,22 +136,42 @@ const composio = new Composio({
136
provider: new MastraProvider(),
137
});
138
125
-// Create an MCP server with the Gmail toolkit
126
-const mcpConfig = await composio.mcp.create(
127
-"Gmail Readonly Server",
128
-[
129
- {
130
- toolkit: "GMAIL",
131
- allowedTools: ["GMAIL_FETCH_EMAILS"],
132
- authConfigId: "<auth_config_id>"
133
- },
134
-],
135
-{ useComposioManagedAuth: true }
136
-);
139
+// Create an MCP server with the Gmail toolkit using new API structure
140
+const mcpConfig = await composio.mcp.create({
141
+ name: "Gmail Readonly Server",
142
+ serverConfig: [
143
+ {
144
+ authConfigId: "<auth_config_id>", // Your auth config ID
145
+ allowedTools: ["GMAIL_FETCH_EMAILS"]
146
+ }
147
+ ],
148
+ options: {
149
+ isChatAuth: true
150
+ }
151
+});
152
153
console.log(`✅ MCP server created: ${mcpConfig.id}`);
154
console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
155
156
+// Check user connection status
157
+const connectionStatus = await composio.mcp.getUserConnectionStatus({
158
+ id: mcpConfig.id,
159
+ userId: "utkarsh-dixit"
160
+});
161
+
162
+console.log("Connection status:", connectionStatus.connected);
163
+
164
+if (!connectionStatus.connected) {
165
+ console.log("❌ User needs to authenticate with required services");
166
+ // Handle authentication flow
167
+ Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
168
+ if (!status.connected) {
169
+ console.log(`Please connect ${toolkit}`);
170
+ }
171
+ });
172
+ return;
173
+}
174
+
175
// Retrieve server instance for connected accounts
176
const serverInstance = await mcpConfig.getServer({
177
userId: "utkarsh-dixit"
@@ -194,42 +228,91 @@ The **OpenAI SDK Provider** is designed for use with the OpenAI SDK and supports
228
<CodeGroupItem title="TypeScript">
229
230
```typescript
231
+import { Composio } from '@composio/core';
232
+import { OpenAIProvider } from '@composio/openai';
233
+import OpenAI from 'openai';
234
+
235
+const openai = new OpenAI({
236
+ apiKey: process.env.OPENAI_API_KEY,
237
+});
238
+
239
const composio = new Composio({
240
apiKey: process.env.COMPOSIO_API_KEY,
199
- provider: new OpenAIResponsesProvider(),
241
+ provider: new OpenAIProvider(),
242
});
243
202
-const mcpConfig = await composio.mcp.create(
203
-"Gmail Readonly Server",
204
-[
205
- {
206
- toolkit: "GMAIL",
207
- allowedTools: ["GMAIL_FETCH_EMAILS"],
208
- authConfigId: "<auth_config_id>"
209
- },
210
-],
211
-{ useComposioManagedAuth: true }
212
-);
244
+// Create MCP server with new API structure
245
+const mcpConfig = await composio.mcp.create({
246
+ name: "Gmail Readonly Server",
247
+ serverConfig: [
248
+ {
249
+ authConfigId: "<auth_config_id>", // Your auth config ID
250
+ allowedTools: ["GMAIL_FETCH_EMAILS"]
251
+ }
252
+ ],
253
+ options: {
254
+ isChatAuth: true
255
+ }
256
+});
257
258
console.log(`✅ MCP server created: ${mcpConfig.id}`);
259
console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(", ")}`);
260
261
+// Check if user has necessary connections
262
+const connectionStatus = await composio.mcp.getUserConnectionStatus({
263
+ id: mcpConfig.id,
264
+ userId: "utkarsh-dixit"
265
+});
266
+
267
+if (!connectionStatus.connected) {
268
+ console.log("❌ User authentication required");
269
+ // Handle missing connections
270
+ for (const [toolkit, status] of Object.entries(connectionStatus.connectedToolkits)) {
271
+ if (!status.connected) {
272
+ const authParams = await composio.mcp.getConnectionParams({
273
+ id: mcpConfig.id,
274
+ toolkit
275
+ });
276
+
277
+ const authRequest = await composio.mcp.authorize({
278
+ id: mcpConfig.id,
279
+ userId: "utkarsh-dixit",
280
+ toolkit
281
+ });
282
+
283
+ if (authRequest.redirectUrl) {
284
+ console.log(`Please authenticate with ${toolkit}: ${authRequest.redirectUrl}`);
285
+ }
286
+ }
287
+ }
288
+ return;
289
+}
290
+
291
// Retrieve server URLs for connected accounts
292
const serverUrls = await mcpConfig.getServer({
293
userId: "utkarsh-dixit",
294
+ options: {
295
+ limitTools: ["GMAIL_FETCH_EMAILS"] // Optional: limit to specific tools
296
+ }
297
});
298
299
console.log("Server URLs for your MCP server:", serverUrls);
300
224
-const completion = await openai.responses.create({
225
-model: "gpt-4o-mini",
226
-input:
227
- "I've connected to Gmail and I want to fetch the latest email from my inbox and summarize it",
228
-tools: serverUrls,
301
+// Use with OpenAI (example with hypothetical OpenAI MCP integration)
302
+const completion = await openai.chat.completions.create({
303
+ model: "gpt-4o-mini",
304
+ messages: [
305
+ {
306
+ role: "user",
307
+ content: "I've connected to Gmail and I want to fetch the latest email from my inbox and summarize it"
308
+ }
309
+ ],
310
+ // Note: This is a hypothetical integration - actual OpenAI MCP support may differ
311
+ tools: serverUrls,
312
});
313
314
console.log("\n📬 Email Summary:");
232
-console.log(completion.output_text);
315
+console.log(completion.choices[0].message.content);
316
317
console.log("\n✅ OpenAI MCP example completed successfully!");
318
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}`);
324
325
---
326
244
-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
327
+## Managing Existing Servers
328
+
329
+You can also work with previously created MCP servers:
330
+
331
+```typescript
332
+// Find a server by name
333
+const existingServer = await composio.mcp.getByName("Gmail Readonly Server");
334
+
335
+// Check connection status for the existing server
336
+const status = await composio.mcp.getUserConnectionStatus({
337
+ id: existingServer.id,
338
+ userId: "user123@example.com"
339
+});
340
+
341
+// Generate URLs for the existing server
342
+const urls = await composio.mcp.getServer({
343
+ id: existingServer.id,
344
+ userId: "user123@example.com",
345
+ options: {
346
+ isChatAuth: true
347
+ }
348
+});
349
+```
350
+
351
+## Best Practices for Providers
352
+
353
+1. **Always check connection status** before using MCP servers to ensure users are authenticated
354
+2. **Handle authentication gracefully** by providing clear instructions and redirect URLs
355
+3. **Use meaningful server names** to make management easier
356
+4. **Limit tools appropriately** to only what your application needs
357
+5. **Cache server configurations** when possible to reduce API calls
358
+6. **Monitor connection health** and provide re-authentication flows when needed
359
+
360
+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 file
ts/examples/openai/src/mcp.ts
+70
-28
@@ -9,7 +9,7 @@
9
*/
10
11
import { OpenAIResponsesProvider } from '@composio/openai';
12
-import { Composio } from '@composio/core';
12
+import { Composio, ConnectionStatus } from '@composio/core';
13
import OpenAI from 'openai';
14
import dotenv from 'dotenv';
15
dotenv.config();
@@ -29,39 +29,81 @@ const openai = new OpenAI({
29
apiKey: process.env.OPENAI_API_KEY,
30
});
31
32
-// Create an MCP server with Gmail toolkit
33
-const mcpConfig = await composio.mcp.create(
34
- "gmail-mcp-openai-" + Date.now(),
35
- [
36
- {
37
- toolkit: "gmail",
38
- authConfigId: "<auth_config_id>", // Replace with your auth config ID
39
- allowedTools: [
40
- "GMAIL_FETCH_EMAILS"
41
- ]
32
+const MCP_SERVER_NAME = "gmail-readonly-server";
33
+const USER_ID = "utkarsah";
34
+
35
+// Check if MCP server with name already exists
36
+let existingServer;
37
+try {
38
+ existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);
39
+ console.log(`✅ Found existing MCP server: ${existingServer.id}`);
40
+} catch (error) {
41
+ // Server doesn't exist, create a new one
42
+ console.log(`📝 Creating new MCP server: ${MCP_SERVER_NAME}`);
43
+
44
+ const mcpConfig = await composio.mcp.create({
45
+ name: MCP_SERVER_NAME,
46
+ serverConfig: [
47
+ {
48
+ authConfigId: "ac_MbbEVd0i1TBG", // Replace with your auth config ID
49
+ allowedTools: [
50
+ "GMAIL_FETCH_EMAILS"
51
+ ]
52
+ }
53
+ ],
54
+ options: {
55
+ // @TODO: Need better name for this
56
+ isChatAuth: true
57
}
43
- ],
44
- { useComposioManagedAuth: true }
45
-);
58
+ });
59
+
60
+ // Get the newly created server details
61
+ existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);
62
+ console.log(`✅ MCP server created: ${existingServer.id}`);
63
+}
64
47
-console.log(`✅ MCP server created: ${mcpConfig.id}`);
48
-console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(', ')}`);
65
+console.log("Server details:", existingServer);
66
50
-// Get server URLs with connected accounts (using convenience method)
51
-const serverUrls = await mcpConfig.getServer({
52
- connectedAccountIds: {
53
- "gmail": "<connected_account_id>" // Replace with your connected account ID
54
- }
67
+const connectionStatus = await composio.mcp.getUserConnectionStatus({
68
+ id: existingServer.id,
69
+ userId: USER_ID,
70
});
71
57
-// Alternative: You can also use the standalone method to get URLs later
58
-// const serverUrls = await composio.mcp.getServer(mcpConfig.id, {
59
-// connectedAccountIds: {
60
-// "gmail": "<connected_account_id>"
61
-// }
72
+console.log("Connection status:", connectionStatus);
73
+const toolkits = connectionStatus.connectedToolkits;
74
+for (let toolkit of Object.values(toolkits)) {
75
+ if(toolkit.type === ConnectionStatus.DISCONNECTED) {
76
+ const requiredParams = await composio.mcp.getConnectionParams({id: existingServer.id, toolkit: toolkit.toolkit});
77
+ console.log("Required params:", requiredParams);
78
+ const connectionStatus = await composio.mcp.authorize({id: existingServer.id, userId: USER_ID, toolkit: toolkit.toolkit});
79
+ console.log("Connection status:", connectionStatus);
80
+if (connectionStatus.redirectUrl) {
81
+ console.log(`Please complete the authentication by visiting the following URL: ${connectionStatus.redirectUrl}`);
82
+ console.log("Press 'Enter' once you have completed the authentication.");
83
+ await new Promise(resolve => process.stdin.once('data', resolve));
84
+}
85
+}
86
+}
87
+
88
+// console.log(`✅ MCP server created: ${mcpConfig.id}`);
89
+// console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(', ')}`);
90
+
91
+// // Get server URLs with user ID (using convenience method)
92
+// const serverUrls = await mcpConfig.getServer({
93
+// userId: "utkarsh" // Replace with your user ID
94
// });
95
64
-console.log("Server URLs for connected accounts:", serverUrls);
96
+// Alternative: You can also use the standalone method to get URLs later
97
+const serverUrls = await composio.mcp.getServer({
98
+ id: existingServer.id,
99
+ userId: USER_ID,
100
+ options: {
101
+ limitTools: ["GMAIL_FETCH_EMAILS"],
102
+ isChatAuth: true
103
+ }
104
+});
105
+
106
+// console.log("Server URLs for user:", serverUrls);
107
108
// Function to fetch and summarize emails
109
async function fetchAndSummarizeEmails() {
@@ -87,4 +129,4 @@ await fetchAndSummarizeEmails();
129
130
console.log('\n✅ OpenAI MCP Example completed successfully!');
131
console.log('\n💡 Note: The MCP server URLs can be used to connect from other MCP-compatible clients');
90
-console.log(`📍 Server ID for future reference: ${mcpConfig.id}`);
132
+console.log(`📍 Server ID for future reference: ${existingServer.id}`);
ts/packages/core/src/models/MCP.ts
+351
-74
@@ -31,6 +31,9 @@ import {
31
GenerateURLResponse,
32
GenerateURLParamsSchema,
33
GenerateURLParams,
34
+ McpToolkitConnectionStatus,
35
+ McpUserConnectionStatus,
36
+ ConnectionStatus,
37
} from '../types/mcp.types';
38
import {
39
CustomCreateResponse as CustomCreateResponseRaw,
@@ -46,6 +49,9 @@ import {
49
transformMcpUpdateResponse,
50
transformMcpGenerateUrlResponse,
51
} from '../utils/transformers/mcp';
52
+import { Toolkits } from './Toolkits';
53
+import { ToolkitAuthFieldsResponse } from '../types/toolkit.types';
54
+import { ConnectionRequest } from '../types/connectionRequest.types';
55
56
/**
57
* MCP (Model Control Protocol) class
@@ -54,10 +60,12 @@ import {
60
export class MCP<T = McpServerGetResponse> {
61
private client: ComposioClient;
62
private provider?: BaseComposioProvider<unknown, unknown, unknown>;
63
+ private toolkits: Toolkits;
64
65
constructor(client: ComposioClient, provider?: BaseComposioProvider<unknown, unknown, unknown>) {
66
this.client = client;
67
this.provider = provider;
68
+ this.toolkits = new Toolkits(client);
69
telemetry.instrument(this);
70
}
71
@@ -90,55 +98,87 @@ export class MCP<T = McpServerGetResponse> {
98
99
/**
100
* Create a new MCP server
93
- * @param {string} name - Unique name for the MCP server
94
- * @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations
95
- * @param {MCPAuthOptions} [authOptions] - Authentication configuration options
101
+ * @param {Object} params - Parameters for creating the MCP server
102
+ * @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
103
+ * @param {Object} params.options - Server creation options
104
+ * @param {string} params.options.name - Unique name for the MCP server
105
+ * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
106
* @returns {Promise<McpServerCreateResponse<T>>} Created server details with instance getter
107
*
108
* @example
109
* ```typescript
100
- * const server = await composio.mcp.create(
101
- * "personal-mcp-server",
102
- * [
110
+ * const server = await composio.mcp.create({
111
+ * serverConfig: [
112
* {
104
- * toolkit: "GMAIL",
105
- * authConfigId: "ac_sdhkjfhjksdk",
106
- * allowedTools: ["GMAIL_FETCH_EMAILS"],
107
- * },
113
+ * authConfigId: "ac_xyz",
114
+ * allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
115
+ * }
116
* ],
109
- * { useComposioManagedAuth: true },
110
- * );
111
- *
112
- * // Option 1: Use convenience method on response
113
- * const urls = await server.getServer({
114
- * connectedAccountIds: { gmail: "account_id" }
117
+ * options: {
118
+ * name: "personal-mcp-server",
119
+ * isChatAuth: true
120
+ * }
121
* });
122
*
117
- * // Option 2: Use standalone method later
118
- * const urlsLater = await composio.mcp.getServer(server.id, {
119
- * connectedAccountIds: { gmail: "account_id" }
123
+ * // Use convenience method on response
124
+ * const urls = await server.getServer({
125
+ * userId: "user123"
126
* });
127
* ```
128
*/
123
- async create(
124
- name: string,
125
- toolkitConfigs: MCPToolkitConfig[],
126
- authOptions?: MCPAuthOptions
127
- ): Promise<McpServerCreateResponse<T>> {
129
+ async create({
130
+ name,
131
+ serverConfig,
132
+ options,
133
+ }: {
134
+ name: string;
135
+ serverConfig: Array<{
136
+ authConfigId: string;
137
+ allowedTools: string[];
138
+ }>;
139
+ options: {
140
+ isChatAuth?: boolean;
141
+ };
142
+ }): Promise<McpServerCreateResponse<T>> {
143
// Validate inputs using Zod schemas
129
- this.validateInputs(toolkitConfigs, authOptions);
144
+ if (!serverConfig || serverConfig.length === 0) {
145
+ throw new ValidationError('At least one auth config is required', {});
146
+ }
147
131
- const toolkits = toolkitConfigs.map(config => config.toolkit);
148
+ if (!name) {
149
+ throw new ValidationError('Server name is required', {});
150
+ }
151
+
152
+ // Check if server with this name already exists
153
+ try {
154
+ await this.getByName(name);
155
+ // If we reach here, server exists
156
+ throw new ValidationError('MCP server with this name already exists', {
157
+ meta: { serverName: name },
158
+ });
159
+ } catch (error) {
160
+ // If error is not about server not found, re-throw it
161
+ if (error instanceof ValidationError && !error.message.includes('not found')) {
162
+ throw error;
163
+ }
164
+ // Server doesn't exist, we can proceed with creation
165
+ }
166
+
167
+ // Get toolkits from auth configs
168
+ const authConfigDetails = await Promise.all(
169
+ serverConfig.map(config => this.client.authConfigs.retrieve(config.authConfigId))
170
+ );
171
+ const toolkits = authConfigDetails.map(config => config.toolkit.slug);
172
173
// Create a custom MCP server with the toolkit configurations
174
let mcpServerCreatedResponse: CustomCreateResponseRaw;
175
try {
176
mcpServerCreatedResponse = await this.client.mcp.custom.create({
137
- name,
177
+ name: name,
178
toolkits: toolkits,
139
- custom_tools: toolkitConfigs.flatMap(config => config.allowedTools),
140
- managed_auth_via_composio: authOptions?.useComposioManagedAuth || false,
141
- auth_config_ids: toolkitConfigs.map(config => config.authConfigId),
179
+ custom_tools: serverConfig.flatMap(config => config.allowedTools),
180
+ managed_auth_via_composio: options.isChatAuth || false,
181
+ auth_config_ids: serverConfig.map(config => config.authConfigId),
182
});
183
} catch (error) {
184
throw new ValidationError('Failed to create MCP server', {
@@ -164,70 +204,261 @@ export class MCP<T = McpServerGetResponse> {
204
toolkits,
205
getServer: async (params: MCPGetServerParams): Promise<T> => {
206
// Delegate to the standalone getServer method
167
- return this.getServer(camelCaseResponse.id, params, authOptions);
207
+ return this.getServer({
208
+ id: camelCaseResponse.id,
209
+ userId: params.userId || Object.keys(params.connectedAccountIds || {})[0] || '',
210
+ options: {
211
+ isChatAuth: options.isChatAuth,
212
+ },
213
+ });
214
},
215
} as McpServerCreateResponse<T>;
216
}
217
218
+ /**
219
+ * Get the connection status of a user for an MCP server
220
+ *
221
+ * Checks whether a user has the necessary connected accounts to use all toolkits
222
+ * configured in the specified MCP server. Returns both overall connection status
223
+ * and individual status for each toolkit.
224
+ *
225
+ * @param {Object} params - Parameters for checking connection status
226
+ * @param {string} params.id - The UUID of the MCP server to check
227
+ * @param {string} params.userId - The ID of the user to check connection status for
228
+ * @returns {Promise<McpUserConnectionStatus>} Complete connection status including:
229
+ * - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)
230
+ * - `connected`: Boolean indicating if user can use the MCP server
231
+ * - `connectedToolkits`: Record mapping each toolkit name to its individual connection status
232
+ *
233
+ * @throws {ValidationError} When MCP server has no toolkits configured
234
+ * @throws {ValidationError} When MCP server retrieval fails
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * // Check if user can access an MCP server with Gmail and Slack toolkits
239
+ * const connectionStatus = await composio.mcp.getUserConnectionStatus({
240
+ * id: 'mcp-server-uuid',
241
+ * userId: 'user123'
242
+ * });
243
+ *
244
+ * if (connectionStatus.connected) {
245
+ * console.log('User can access all required toolkits');
246
+ * // connectionStatus.type === ConnectionStatus.CONNECTED
247
+ * } else {
248
+ * console.log('User is missing some toolkit connections');
249
+ * // Check individual toolkit statuses
250
+ * Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
251
+ * if (!status.connected) {
252
+ * console.log(`Missing connection for toolkit: ${toolkit}`);
253
+ * }
254
+ * });
255
+ * }
256
+ * ```
257
+ *
258
+ * @example
259
+ * ```typescript
260
+ * // Example response when user has Gmail connected but missing Slack
261
+ * {
262
+ * type: ConnectionStatus.DISCONNECTED,
263
+ * connected: false,
264
+ * connectedToolkits: {
265
+ * GMAIL: {
266
+ * type: ConnectionStatus.CONNECTED,
267
+ * connected: true,
268
+ * toolkit: 'GMAIL',
269
+ * connectedAccountId: 'conn_gmail_123'
270
+ * },
271
+ * SLACK: {
272
+ * type: ConnectionStatus.DISCONNECTED,
273
+ * connected: false,
274
+ * toolkit: 'SLACK'
275
+ * }
276
+ * }
277
+ * }
278
+ * ```
279
+ */
280
+ async getUserConnectionStatus({
281
+ id,
282
+ userId,
283
+ }: {
284
+ id: string;
285
+ userId: string;
286
+ }): Promise<McpUserConnectionStatus> {
287
+ const serverDetails = await this.get(id);
288
+
289
+ if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) {
290
+ throw new ValidationError('MCP server has no toolkits configured', {
291
+ meta: { serverId: id },
292
+ });
293
+ }
294
+
295
+ // @TODO(utkarsh-dixit): Add auth_config_ids support here
296
+ const connectedAccounts = await this.client.connectedAccounts.list({
297
+ user_ids: [userId],
298
+ toolkit_slugs: serverDetails.toolkits.map(toolkit => toolkit.toLowerCase()),
299
+ statuses: ['ACTIVE'],
300
+ });
301
+
302
+ const connectedAccountsByToolkit = new Map<string, string>();
303
+ connectedAccounts.items?.forEach(account => {
304
+ connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);
305
+ });
306
+
307
+ const connectedToolkits: Record<string, McpToolkitConnectionStatus> = {};
308
+ let allToolkitsConnected = true;
309
+
310
+ for (const toolkit of serverDetails.toolkits) {
311
+ const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());
312
+
313
+ if (connectedAccountId) {
314
+ connectedToolkits[toolkit] = {
315
+ type: ConnectionStatus.CONNECTED,
316
+ connected: true,
317
+ toolkit,
318
+ connectedAccountId,
319
+ };
320
+ } else {
321
+ connectedToolkits[toolkit] = {
322
+ type: ConnectionStatus.DISCONNECTED,
323
+ connected: false,
324
+ toolkit,
325
+ };
326
+ allToolkitsConnected = false;
327
+ }
328
+ }
329
+
330
+ if (allToolkitsConnected) {
331
+ return {
332
+ type: ConnectionStatus.CONNECTED,
333
+ connected: true,
334
+ connectedToolkits,
335
+ };
336
+ } else {
337
+ return {
338
+ type: ConnectionStatus.DISCONNECTED,
339
+ connected: false,
340
+ connectedToolkits,
341
+ };
342
+ }
343
+ }
344
+
345
+ async getConnectionParams({
346
+ id,
347
+ toolkit,
348
+ }: {
349
+ id: string;
350
+ toolkit: string;
351
+ }): Promise<ToolkitAuthFieldsResponse> {
352
+ const mcpServerDetails = await this.get(id);
353
+ const authConfigs = mcpServerDetails.authConfigIds
354
+ ? await Promise.all(
355
+ mcpServerDetails.authConfigIds.map(id => this.client.authConfigs.retrieve(id))
356
+ )
357
+ : [];
358
+
359
+ const authConfig = authConfigs.find(config => config.toolkit.slug === toolkit);
360
+ if (!authConfig) {
361
+ throw new ValidationError('Auth config not found', {
362
+ meta: { serverId: id, toolkit },
363
+ });
364
+ }
365
+
366
+ const connectionParams = await this.toolkits.getConnectedAccountInitiationFields(
367
+ toolkit,
368
+ authConfig.auth_scheme!
369
+ );
370
+ return connectionParams;
371
+ }
372
+
373
+ async authorize({
374
+ id,
375
+ userId,
376
+ toolkit,
377
+ }: {
378
+ id: string;
379
+ userId: string;
380
+ toolkit: string;
381
+ }): Promise<ConnectionRequest> {
382
+ const mcpServerDetails = await this.get(id);
383
+ const authConfigId = mcpServerDetails.authConfigIds?.[0];
384
+ return this.toolkits.authorize(userId, toolkit, authConfigId);
385
+ }
386
+
387
/**
388
* Get server URLs for an existing MCP server
174
- * @param {string} id - Server UUID
175
- * @param {MCPGetServerParams} params - Parameters for getting server URLs
176
- * @param {MCPAuthOptions} [authOptions] - Authentication options (optional, will use server's default if not provided)
389
+ * @param {Object} params - Parameters for getting server URLs
390
+ * @param {string} params.id - Server UUID
391
+ * @param {string} params.userId - User ID to get server URLs for
392
+ * @param {Object} [params.options] - Additional options for server configuration
393
+ * @param {string[]} [params.options.limitTools] - Subset of tools to limit (from MCP config)
394
+ * @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
395
* @returns {Promise<T>} Transformed server URLs in provider-specific format
396
*
397
* @example
398
* ```typescript
181
- * // Get URLs for an existing server
182
- * const urls = await composio.mcp.getServer("server-id", {
183
- * connectedAccountIds: {
184
- * gmail: "connected_account_id"
399
+ * // Get URLs for an existing server with basic user ID
400
+ * const urls = await composio.mcp.getServer({
401
+ * id: "mcp_xyz",
402
+ * userId: "hey@example.com"
403
+ * });
404
+ *
405
+ * // Get URLs with additional options
406
+ * const urls = await composio.mcp.getServer({
407
+ * id: "mcp_xyz",
408
+ * userId: "hey@example.com",
409
+ * options: {
410
+ * limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
411
+ * isChatAuth: true
412
* }
413
* });
414
* ```
415
*/
189
- async getServer(
190
- id: string,
191
- params: MCPGetServerParams,
192
- authOptions?: MCPAuthOptions
193
- ): Promise<T> {
416
+ async getServer({
417
+ id,
418
+ userId,
419
+ options,
420
+ }: {
421
+ id: string;
422
+ userId: string;
423
+ options?: {
424
+ limitTools?: string[];
425
+ isChatAuth?: boolean;
426
+ };
427
+ }): Promise<T> {
428
// Get server details first
429
const serverDetails = await this.get(id);
430
197
- // Validate params using Zod schema
198
- const paramsResult = MCPGetServerParamsSchema.safeParse(params);
199
- if (paramsResult.error) {
200
- throw new ValidationError('Failed to parse get server parameters', {
201
- cause: paramsResult.error,
202
- });
431
+ // Validate userId is provided
432
+ if (!userId) {
433
+ throw new ValidationError('User ID is required', {});
434
}
435
436
// Extract toolkits from server details
437
const toolkits = serverDetails.toolkits || [];
438
208
- // If connected_account_ids is provided, verify toolkit names
209
- if (paramsResult.data.connectedAccountIds) {
210
- const providedToolkits = Object.keys(paramsResult.data.connectedAccountIds);
211
- const invalidToolkits = providedToolkits.filter(toolkit => !toolkits.includes(toolkit));
212
- if (invalidToolkits.length > 0) {
213
- throw new ValidationError(
214
- `Invalid toolkits provided: ${invalidToolkits.join(', ')}. Available toolkits are: ${toolkits.join(', ')}`,
215
- {}
216
- );
217
- }
218
- }
439
+ const connectedAccountIds = (
440
+ await Promise.all(
441
+ toolkits.map(toolkit =>
442
+ this.client.connectedAccounts
443
+ .list({
444
+ user_ids: [userId],
445
+ toolkit_slugs: [toolkit],
446
+ statuses: ['ACTIVE'],
447
+ })
448
+ .then(res => res.items?.[0]?.id)
449
+ )
450
+ )
451
+ ).filter(Boolean);
452
453
// Generate URL with error handling
454
let data;
455
try {
456
data = await this.client.mcp.generate.url({
224
- user_ids: paramsResult.data.userId ? [paramsResult.data.userId] : [],
225
- connected_account_ids: paramsResult.data.connectedAccountIds
226
- ? Object.values(paramsResult.data.connectedAccountIds)
227
- : [],
457
+ user_ids: [userId],
458
+ connected_account_ids: connectedAccountIds,
459
mcp_server_id: id,
460
managed_auth_by_composio:
230
- authOptions?.useComposioManagedAuth ?? serverDetails.managedAuthViaComposio ?? false,
461
+ options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false,
462
});
463
} catch (error) {
464
throw new ValidationError('Failed to generate MCP server URL', {
@@ -250,13 +481,9 @@ export class MCP<T = McpServerGetResponse> {
481
return this.wrapMcpServerResponse(
482
camelCaseData,
483
serverDetails.name,
253
- paramsResult.data.connectedAccountIds
254
- ? Object.values(paramsResult.data.connectedAccountIds)
255
- : undefined,
256
- paramsResult.data.userId ? [paramsResult.data.userId] : undefined,
257
- paramsResult.data.connectedAccountIds
258
- ? Object.keys(paramsResult.data.connectedAccountIds)
259
- : undefined
484
+ connectedAccountIds,
485
+ [userId],
486
+ toolkits
487
);
488
}
489
@@ -299,8 +526,8 @@ export class MCP<T = McpServerGetResponse> {
526
listResponse = await this.client.mcp.list({
527
page_no: options.page || 1,
528
limit: options.limit || 10,
302
- toolkits: options?.toolkits?.join(',') || '',
303
- auth_config_ids: options?.authConfigs?.join(',') || '',
529
+ toolkits: options?.toolkits?.join(',') || undefined,
530
+ auth_config_ids: options?.authConfigs?.join(',') || undefined,
531
name: options?.name,
532
});
533
} catch (error) {
@@ -566,4 +793,54 @@ export class MCP<T = McpServerGetResponse> {
793
name: serverName,
794
} as T;
795
}
796
+
797
+ /**
798
+ * Get details of a specific MCP server by name
799
+ * @param {string} name - Server name
800
+ * @returns {Promise<McpRetrieveResponse>} Server details
801
+ * @throws {ValidationError} If no server found with the given name
802
+ * @throws {ValidationError} If multiple servers found with the same name
803
+ *
804
+ * @example
805
+ * ```typescript
806
+ * const serverDetails = await composio.mcp.getByName('my-gmail-server');
807
+ * ```
808
+ */
809
+ async getByName(name: string): Promise<McpRetrieveResponse> {
810
+ if (!name) {
811
+ throw new ValidationError('Server name is required', {});
812
+ }
813
+
814
+ // List MCP servers filtered by name
815
+ let listResponse;
816
+ try {
817
+ listResponse = await this.client.mcp.list({
818
+ name: name,
819
+ limit: 10,
820
+ });
821
+ } catch (error) {
822
+ throw new ValidationError('Failed to search MCP servers by name', {
823
+ cause: error,
824
+ });
825
+ }
826
+
827
+ // Validate the list response
828
+ const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
829
+ if (listResponseResult.error) {
830
+ throw new ValidationError('Failed to parse MCP server list response', {
831
+ cause: listResponseResult.error,
832
+ });
833
+ }
834
+
835
+ const servers = listResponse.items || [];
836
+
837
+ if (servers.length === 0) {
838
+ throw new ValidationError(`MCP server with name '${name}' not found`, {
839
+ meta: { serverName: name },
840
+ });
841
+ }
842
+
843
+ // Get the full server details using the server ID
844
+ return this.get(servers[0].id);
845
+ }
846
}
ts/packages/core/src/models/Toolkits.ts
+14
-7
@@ -374,15 +374,22 @@ export class Toolkits {
374
* const connectionRequest = await composio.toolkits.authorize(userId, 'github');
375
* ```
376
*/
377
- async authorize(userId: string, toolkitSlug: string): Promise<ConnectionRequest> {
377
+ async authorize(
378
+ userId: string,
379
+ toolkitSlug: string,
380
+ authConfigId?: string
381
+ ): Promise<ConnectionRequest> {
382
const toolkit = await this.getToolkitBySlug(toolkitSlug);
383
const composioAuthConfig = new AuthConfigs(this.client);
380
- let authConfigIdToUse: string;
381
- const authConfig = await composioAuthConfig.list({
382
- toolkit: toolkitSlug,
383
- });
384
- // pick the first auth config
385
- authConfigIdToUse = authConfig.items[0]?.id;
384
+ let authConfigIdToUse: string | undefined = authConfigId;
385
+
386
+ if (!authConfigIdToUse) {
387
+ const authConfig = await composioAuthConfig.list({
388
+ toolkit: toolkitSlug,
389
+ });
390
+ // pick the first auth config if none is passed
391
+ authConfigIdToUse = authConfig.items[0]?.id;
392
+ }
393
394
// if no auth config is found, create one for the toolkit
395
if (!authConfigIdToUse) {
ts/packages/core/src/types/mcp.types.ts
+31
@@ -202,6 +202,36 @@ export type McpServerCreateResponse<T> = (McpCreateResponseRaw | CustomCreateRes
202
getServer: (params: MCPGetServerParams) => Promise<T>;
203
};
204
205
+export enum ConnectionStatus {
206
+ CONNECTED = 'CONNECTED',
207
+ DISCONNECTED = 'DISCONNECTED',
208
+}
209
+
210
+export type McpToolkitConnectionStatus =
211
+ | {
212
+ type: ConnectionStatus.CONNECTED;
213
+ connected: true;
214
+ toolkit: string;
215
+ connectedAccountId: string;
216
+ }
217
+ | {
218
+ type: ConnectionStatus.DISCONNECTED;
219
+ connected: false;
220
+ toolkit: string;
221
+ };
222
+
223
+export type McpUserConnectionStatus =
224
+ | {
225
+ type: ConnectionStatus.CONNECTED;
226
+ connected: true;
227
+ connectedToolkits: Record<string, McpToolkitConnectionStatus>;
228
+ }
229
+ | {
230
+ type: ConnectionStatus.DISCONNECTED;
231
+ connected: false;
232
+ connectedToolkits: Record<string, McpToolkitConnectionStatus>;
233
+ };
234
+
235
// CamelCase create response schema
236
export const CustomCreateResponseSchema = z.object({
237
id: z.string().min(1, 'Server ID cannot be empty'),
@@ -263,6 +293,7 @@ export const McpRetrieveResponseSchema = z.object({
293
toolkits: z.array(z.string()).optional(),
294
tools: z.array(z.string()).optional(),
295
managedAuthViaComposio: z.boolean().optional(),
296
+ authConfigIds: z.array(z.string()).optional(),
297
});
298
299
// Snake_case retrieve response schema (for API)
ts/packages/core/src/utils/transformers/mcp.ts
+1
@@ -86,6 +86,7 @@ export function transformMcpRetrieveResponse(
86
toolkits: response.toolkits,
87
tools: (response as unknown as Record<string, unknown>).tools,
88
managedAuthViaComposio: response.managed_auth_via_composio,
89
+ authConfigIds: response.auth_config_ids,
90
});
91
92
if (!result.success) {
ts/packages/core/test/models/mcp.test.ts
+120
-99
@@ -100,6 +100,15 @@ const createMockClient = () => ({
100
delete: vi.fn(),
101
update: vi.fn(),
102
},
103
+ authConfigs: {
104
+ retrieve: vi.fn(),
105
+ },
106
+ connectedAccounts: {
107
+ list: vi.fn(),
108
+ },
109
+ toolkits: {
110
+ retrieve: vi.fn(),
111
+ },
112
});
113
114
// Mock response data
@@ -207,19 +216,31 @@ describe('MCP', () => {
216
});
217
218
describe('create', () => {
210
- const toolkitConfigs = [
219
+ const serverConfig = [
220
{
212
- toolkit: 'gmail',
221
authConfigId: 'ac_gmail123',
222
allowedTools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'],
223
},
224
];
225
226
+ beforeEach(() => {
227
+ // Mock authConfigs.retrieve to return toolkit information
228
+ mockClient.authConfigs.retrieve.mockResolvedValue({
229
+ id: 'ac_gmail123',
230
+ toolkit: { slug: 'gmail' },
231
+ auth_scheme: 'OAUTH2',
232
+ });
233
+ });
234
+
235
it('should create an MCP server successfully', async () => {
236
mockClient.mcp.custom.create.mockResolvedValue(mockCreateResponse);
237
221
- const result = await mcp.create('test-server', toolkitConfigs, {
222
- useComposioManagedAuth: true,
238
+ const result = await mcp.create({
239
+ name: 'test-server',
240
+ serverConfig,
241
+ options: {
242
+ isChatAuth: true,
243
+ },
244
});
245
246
expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
@@ -240,53 +261,44 @@ describe('MCP', () => {
261
expect(typeof result.getServer).toBe('function');
262
});
263
243
- it('should validate toolkit configurations', async () => {
244
- const invalidConfigs = [
245
- {
246
- toolkit: '', // Empty toolkit
247
- authConfigId: 'ac_123',
248
- allowedTools: ['TOOL_1'],
249
- },
250
- ];
251
-
252
- await expect(mcp.create('test-server', invalidConfigs)).rejects.toThrow(ValidationError);
253
- });
254
-
255
- it('should validate auth options', async () => {
256
- const invalidAuthOptions = {
257
- useComposioManagedAuth: 'true' as unknown as boolean, // Should be boolean
258
- };
264
+ it('should validate server configuration', async () => {
265
+ const invalidConfigs: any[] = []; // Empty array
266
260
- await expect(mcp.create('test-server', toolkitConfigs, invalidAuthOptions)).rejects.toThrow(
261
- ValidationError
262
- );
267
+ await expect(
268
+ mcp.create({
269
+ name: 'test-server',
270
+ serverConfig: invalidConfigs,
271
+ options: {
272
+ isChatAuth: true,
273
+ },
274
+ })
275
+ ).rejects.toThrow('At least one auth config is required');
276
});
277
265
- it('should throw ValidationError when duplicate toolkits are provided', async () => {
266
- const duplicateConfigs = [
267
- {
268
- toolkit: 'gmail',
269
- authConfigId: 'ac_gmail123',
270
- allowedTools: ['GMAIL_FETCH_EMAILS'],
271
- },
272
- {
273
- toolkit: 'gmail',
274
- authConfigId: 'ac_gmail456',
275
- allowedTools: ['GMAIL_SEND_EMAIL'],
276
- },
277
- ];
278
-
279
- await expect(mcp.create('test-server', duplicateConfigs)).rejects.toThrow(
280
- 'Duplicate toolkits are not allowed'
281
- );
278
+ it('should validate server name', async () => {
279
+ await expect(
280
+ mcp.create({
281
+ name: '',
282
+ serverConfig,
283
+ options: {
284
+ isChatAuth: true,
285
+ },
286
+ })
287
+ ).rejects.toThrow('Server name is required');
288
});
289
290
it('should handle server creation errors', async () => {
291
mockClient.mcp.custom.create.mockRejectedValue(new Error('Server creation failed'));
292
287
- await expect(mcp.create('test-server', toolkitConfigs)).rejects.toThrow(
288
- 'Failed to create MCP server'
289
- );
293
+ await expect(
294
+ mcp.create({
295
+ name: 'test-server',
296
+ serverConfig,
297
+ options: {
298
+ isChatAuth: true,
299
+ },
300
+ })
301
+ ).rejects.toThrow('Failed to create MCP server');
302
});
303
});
304
@@ -303,20 +315,26 @@ describe('MCP', () => {
315
tools: mockRetrieveResponse.tools,
316
managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
317
});
318
+
319
+ // Mock connectedAccounts.list
320
+ mockClient.connectedAccounts.list.mockResolvedValue({
321
+ items: [
322
+ { id: 'account_123', toolkit: { slug: 'gmail' } },
323
+ { id: 'account_456', toolkit: { slug: 'github' } },
324
+ ],
325
+ });
326
});
327
308
- it('should get server URLs with connected account IDs', async () => {
328
+ it('should get server URLs with user ID', async () => {
329
mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
330
311
- const result = await mcp.getServer('mcp_123', {
312
- connectedAccountIds: {
313
- gmail: 'account_123',
314
- github: 'account_456',
315
- },
331
+ const result = await mcp.getServer({
332
+ id: 'mcp_123',
333
+ userId: 'user_123',
334
});
335
336
expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
319
- user_ids: [],
337
+ user_ids: ['user_123'],
338
connected_account_ids: ['account_123', 'account_456'],
339
mcp_server_id: 'mcp_123',
340
managed_auth_by_composio: true,
@@ -325,44 +343,33 @@ describe('MCP', () => {
343
expect(result).toBeDefined();
344
});
345
328
- it('should get server URLs with user ID', async () => {
346
+ it('should get server URLs with options', async () => {
347
mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
348
331
- const result = await mcp.getServer('mcp_123', {
349
+ const result = await mcp.getServer({
350
+ id: 'mcp_123',
351
userId: 'user_123',
352
+ options: {
353
+ limitTools: ['GMAIL_FETCH_EMAILS'],
354
+ isChatAuth: false,
355
+ },
356
});
357
358
expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
359
user_ids: ['user_123'],
337
- connected_account_ids: [],
360
+ connected_account_ids: ['account_123', 'account_456'],
361
mcp_server_id: 'mcp_123',
339
- managed_auth_by_composio: true,
362
+ managed_auth_by_composio: false,
363
});
364
});
365
343
- it('should validate that either userId or connectedAccountIds is provided', async () => {
344
- await expect(mcp.getServer('mcp_123', {})).rejects.toThrow(
345
- 'Must provide either userId or connectedAccountIds, but not both'
346
- );
347
- });
348
-
349
- it('should validate that both userId and connectedAccountIds are not provided', async () => {
366
+ it('should validate that userId is provided', async () => {
367
await expect(
351
- mcp.getServer('mcp_123', {
352
- userId: 'user_123',
353
- connectedAccountIds: { gmail: 'account_123' },
368
+ mcp.getServer({
369
+ id: 'mcp_123',
370
+ userId: '',
371
})
355
- ).rejects.toThrow('Must provide either userId or connectedAccountIds, but not both');
356
- });
357
-
358
- it('should validate toolkit names in connectedAccountIds', async () => {
359
- await expect(
360
- mcp.getServer('mcp_123', {
361
- connectedAccountIds: {
362
- slack: 'account_123', // Not in server's toolkits
363
- },
364
- })
365
- ).rejects.toThrow('Invalid toolkits provided: slack');
372
+ ).rejects.toThrow('User ID is required');
373
});
374
375
it('should use custom provider transformation', async () => {
@@ -386,7 +393,8 @@ describe('MCP', () => {
393
};
394
mockClient.mcp.generate.url.mockResolvedValue(singleUserResponse);
395
389
- const result = await mcpWithProvider.getServer('mcp_123', {
396
+ const result = await mcpWithProvider.getServer({
397
+ id: 'mcp_123',
398
userId: 'user_123',
399
});
400
@@ -615,15 +623,20 @@ describe('MCP', () => {
623
mockClient.mcp.retrieve.mockResolvedValue(mockRetrieveResponse);
624
mockClient.mcp.generate.url.mockResolvedValue(mockGenerateUrlResponse);
625
618
- const toolkitConfigs = [
626
+ const serverConfig = [
627
{
620
- toolkit: 'gmail',
628
authConfigId: 'ac_gmail123',
629
allowedTools: ['GMAIL_FETCH_EMAILS'],
630
},
631
];
632
626
- const server = await mcp.create('test-server', toolkitConfigs);
633
+ const server = await mcp.create({
634
+ name: 'test-server',
635
+ serverConfig,
636
+ options: {
637
+ isChatAuth: true,
638
+ },
639
+ });
640
641
// Mock the internal get call
642
vi.spyOn(mcp, 'get').mockResolvedValue({
@@ -637,8 +650,13 @@ describe('MCP', () => {
650
managedAuthViaComposio: mockRetrieveResponse.managed_auth_via_composio,
651
});
652
653
+ // Mock connectedAccounts.list for the convenience method
654
+ mockClient.connectedAccounts.list.mockResolvedValue({
655
+ items: [{ id: 'account_123', toolkit: { slug: 'gmail' } }],
656
+ });
657
+
658
const urls = await server.getServer({
641
- connectedAccountIds: { gmail: 'account_123' },
659
+ userId: 'user123',
660
});
661
662
expect(urls).toBeDefined();
@@ -647,32 +665,35 @@ describe('MCP', () => {
665
});
666
667
describe('validation error messages', () => {
650
- it('should provide meaningful error messages for toolkit config validation', async () => {
651
- const invalidConfigs = [
652
- {
653
- toolkit: 'gmail',
654
- authConfigId: '', // Empty auth config ID
655
- allowedTools: ['GMAIL_FETCH_EMAILS'],
656
- },
657
- ];
658
-
659
- await expect(mcp.create('test-server', invalidConfigs)).rejects.toThrow(
660
- 'Auth config ID cannot be empty'
661
- );
668
+ it('should provide meaningful error messages for empty auth config', async () => {
669
+ await expect(
670
+ mcp.create({
671
+ name: 'test-server',
672
+ serverConfig: [],
673
+ options: {
674
+ isChatAuth: true,
675
+ },
676
+ })
677
+ ).rejects.toThrow('At least one auth config is required');
678
});
679
664
- it('should provide meaningful error messages for empty allowed tools', async () => {
665
- const invalidConfigs = [
680
+ it('should provide meaningful error messages for empty server name', async () => {
681
+ const serverConfig = [
682
{
667
- toolkit: 'gmail',
683
authConfigId: 'ac_123',
669
- allowedTools: [], // Empty tools array
684
+ allowedTools: ['GMAIL_FETCH_EMAILS'],
685
},
686
];
687
673
- await expect(mcp.create('test-server', invalidConfigs)).rejects.toThrow(
674
- 'At least one tool must be specified'
675
- );
688
+ await expect(
689
+ mcp.create({
690
+ name: '',
691
+ serverConfig,
692
+ options: {
693
+ isChatAuth: true,
694
+ },
695
+ })
696
+ ).rejects.toThrow('Server name is required');
697
});
698
});
699
});