@devries-cameron20 / composio-1 / commits / 155887a67
Fork 0

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

Add allow_multiple option to Python SDK for connected accounts

Prateek committed Sep 29, 2025 at 15:37 UTC 155887a676e65eca83441c615a9ae8c283815b00
3 files changed +229 -1
python/composio/core/models/connected_accounts.py
+23 -1
@@ -1,6 +1,7 @@
1 from __future__ import annotations
2
3 import functools
4 +import logging
5 import time
6 import typing as t
7
@@ -16,6 +17,8 @@ from composio.client.types import (
17
18 from .base import Resource
19
20 +logger = logging.getLogger(__name__)
21 +
22
23 class ConnectionRequest(Resource):
24 """
@@ -320,6 +323,7 @@ class ConnectedAccounts:
323 *,
324 callback_url: t.Optional[str] = None,
325 config: t.Optional[connected_account_create_params.ConnectionState] = None,
326 + allow_multiple: bool = False,
327 ) -> ConnectionRequest:
328 """
329 Compound function to create a new connected account. This function creates
@@ -331,9 +335,27 @@ class ConnectedAccounts:
335 :param user_id: The user ID to create the connected account for.
336 :param auth_config_id: The auth config ID to create the connected account for.
337 :param callback_url: Callback URL to use for OAuth apps.
334 - :param options: The options to create the connected account with.
338 + :param config: The configuration to create the connected account with.
339 + :param allow_multiple: Whether to allow multiple connected accounts for the same user and auth config.
340 :return: The connection request.
341 """
342 + # Check if there are multiple connected accounts for the authConfig of the user
343 + connected_accounts = self.list(
344 + user_ids=[user_id],
345 + auth_config_ids=[auth_config_id],
346 + )
347 + if connected_accounts.items and not allow_multiple:
348 + raise exceptions.ComposioMultipleConnectedAccountsError(
349 + f"Multiple connected accounts found for user {user_id} in auth config {auth_config_id}. "
350 + "Please use the allow_multiple option to allow multiple connected accounts."
351 + )
352 + elif connected_accounts.items:
353 + logger.warning(
354 + "[Warn:AllowMultiple] Multiple connected accounts found for user %s in auth config %s",
355 + user_id,
356 + auth_config_id,
357 + )
358 +
359 connection: dict[str, t.Any] = {"user_id": user_id}
360 if callback_url is not None:
361 connection["callback_url"] = callback_url
python/composio/exceptions.py
+5
@@ -247,6 +247,11 @@ class InvalidConnectedAccount(ValidationError, ConnectedAccountError):
247 pass
248
249
250 +class ComposioMultipleConnectedAccountsError(ConnectedAccountError):
251 + """Raised when multiple connected accounts are found for a user and auth config."""
252 + pass
253 +
254 +
255 class ErrorProcessingToolExecutionRequest(PluginError):
256 pass
257
python/composio/integration_test/test_mcp_workflow_demo.py new
+201
@@ -0,0 +1,201 @@
1 +#!/usr/bin/env python3
2 +"""
3 +MCP Workflow Demo - Complete end-to-end test.
4 +
5 +This script demonstrates a complete MCP workflow:
6 +1. Create MCP server with composio_search and text_to_pdf toolkits
7 +2. Generate server instance for a user
8 +3. Connect to the MCP server
9 +4. Use the tools through MCP protocol
10 +5. Demonstrate real tool execution
11 +"""
12 +
13 +import os
14 +import time
15 +import json
16 +import requests
17 +from composio import Composio
18 +
19 +def create_mcp_server_with_tools():
20 + """Create MCP server with search and PDF tools."""
21 +
22 + composio = Composio()
23 +
24 + server_name = f'demo-workflow-{int(time.time()) % 1000000}'
25 +
26 + print(f"🏗️ Creating MCP server: {server_name}")
27 +
28 + mcp_server = composio.experimental.mcp.create(server_name, {
29 + 'toolkits': [
30 + {
31 + 'toolkit': 'composio_search',
32 + 'allowed_tools': ['COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH']
33 + },
34 + {
35 + 'toolkit': 'text_to_pdf',
36 + 'allowed_tools': ['TEXT_TO_PDF_CONVERT_TEXT_TO_PDF']
37 + }
38 + ],
39 + 'manually_manage_connections': False
40 + })
41 +
42 + print(f"✅ MCP server created!")
43 + print(f" Server ID: {mcp_server.id}")
44 + print(f" Available Tools: COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH, TEXT_TO_PDF_CONVERT_TEXT_TO_PDF")
45 +
46 + return mcp_server
47 +
48 +def generate_user_instance(mcp_server, user_id):
49 + """Generate MCP server instance for a specific user."""
50 +
51 + print(f"\n👤 Generating server instance for user: {user_id}")
52 +
53 + server_instance = mcp_server.generate(user_id)
54 +
55 + print(f"✅ Server instance generated!")
56 + print(f" Instance URL: {server_instance['url']}")
57 + print(f" Instance Type: {server_instance['type']}")
58 + print(f" User ID: {server_instance['user_id']}")
59 +
60 + return server_instance
61 +
62 +def test_mcp_server_connectivity(server_instance):
63 + """Test basic connectivity to the MCP server."""
64 +
65 + print(f"\n🔌 Testing MCP server connectivity...")
66 +
67 + mcp_url = server_instance['url']
68 +
69 + try:
70 + headers = {
71 + 'Accept': 'text/event-stream, application/json, */*',
72 + 'Cache-Control': 'no-cache',
73 + 'User-Agent': 'Composio-MCP-Demo'
74 + }
75 +
76 + response = requests.get(mcp_url, headers=headers, timeout=10, stream=True)
77 +
78 + if response.status_code == 200:
79 + print(f"✅ MCP server is accessible!")
80 + print(f" Status: {response.status_code}")
81 + print(f" Content-Type: {response.headers.get('Content-Type')}")
82 +
83 + # Read first few events
84 + events = []
85 + for i, chunk in enumerate(response.iter_content(chunk_size=1024, decode_unicode=True)):
86 + if chunk.strip():
87 + events.append(chunk.strip())
88 + if i >= 2: # Read first few chunks
89 + break
90 +
91 + print(f" Initial Events: {len(events)} events received")
92 + for j, event in enumerate(events[:2]):
93 + print(f" Event {j+1}: {event[:80]}...")
94 +
95 + return True
96 + else:
97 + print(f"❌ MCP server returned status: {response.status_code}")
98 + return False
99 +
100 + except requests.exceptions.Timeout:
101 + print(f"⚠️ Connection timeout (normal for SSE endpoints)")
102 + return True # Timeout is actually expected for SSE
103 + except Exception as e:
104 + print(f"❌ Connection failed: {e}")
105 + return False
106 +
107 +def demonstrate_tool_availability(server_instance):
108 + """Demonstrate that tools are available through the MCP server."""
109 +
110 + print(f"\n🛠️ Tool Availability Check:")
111 +
112 + tools = server_instance.get('allowed_tools', [])
113 + print(f" Available Tools: {len(tools)}")
114 +
115 + for i, tool in enumerate(tools, 1):
116 + print(f" {i}. {tool}")
117 +
118 + # Describe what each tool does
119 + if 'DUCK_DUCK_GO_SEARCH' in tool:
120 + print(f" 📍 Performs web searches using DuckDuckGo")
121 + elif 'TEXT_TO_PDF' in tool:
122 + print(f" 📄 Converts text content to PDF format")
123 +
124 + return len(tools) > 0
125 +
126 +def demonstrate_mcp_usage_example():
127 + """Show how the MCP server would be used in practice."""
128 +
129 + print(f"\n💡 MCP Usage Example:")
130 + print(f" Once connected to the MCP server, you could:")
131 + print(f" ")
132 + print(f" 1. 🔍 Search for information:")
133 + print(f" Tool: COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH")
134 + print(f" Input: {{'query': 'Python MCP protocol'}}")
135 + print(f" Output: Search results with titles, snippets, and URLs")
136 + print(f" ")
137 + print(f" 2. 📝 Convert search results to PDF:")
138 + print(f" Tool: TEXT_TO_PDF_CONVERT_TEXT_TO_PDF")
139 + print(f" Input: {{'text': 'Search results content...'}}")
140 + print(f" Output: PDF file with the content")
141 + print(f" ")
142 + print(f" 🔗 Complete workflow:")
143 + print(f" Search → Extract content → Convert to PDF → Save/Share")
144 +
145 +def main():
146 + """Main demo function."""
147 +
148 + # Check API key
149 + api_key = os.getenv('COMPOSIO_API_KEY')
150 + if not api_key:
151 + print("❌ COMPOSIO_API_KEY environment variable not set")
152 + return False
153 +
154 + print("🎯 MCP Workflow Demo")
155 + print("=" * 50)
156 + print("Demonstrating complete MCP workflow with composio_search and text_to_pdf")
157 + print()
158 +
159 + try:
160 + # Step 1: Create MCP server
161 + mcp_server = create_mcp_server_with_tools()
162 +
163 + # Step 2: Generate user instance
164 + user_id = f'demo_user_{int(time.time()) % 10000}'
165 + server_instance = generate_user_instance(mcp_server, user_id)
166 +
167 + # Step 3: Test connectivity
168 + connectivity_ok = test_mcp_server_connectivity(server_instance)
169 +
170 + # Step 4: Check tool availability
171 + tools_available = demonstrate_tool_availability(server_instance)
172 +
173 + # Step 5: Show usage examples
174 + demonstrate_mcp_usage_example()
175 +
176 + # Summary
177 + print(f"\n📊 Demo Summary:")
178 + print(f" ✅ MCP Server Created: {mcp_server.id}")
179 + print(f" ✅ User Instance Generated: {server_instance['user_id']}")
180 + print(f" ✅ Server Connectivity: {'Working' if connectivity_ok else 'Failed'}")
181 + print(f" ✅ Tools Available: {len(server_instance.get('allowed_tools', []))} tools")
182 + print(f" ✅ Auth Required: {'No' if not server_instance.get('auth_configs') else 'Yes'}")
183 + print(f" ✅ Server Type: {server_instance['type']}")
184 +
185 + print(f"\n🎉 MCP Workflow Demo Complete!")
186 + print(f" Your MCP server is ready to use at:")
187 + print(f" {server_instance['url']}")
188 + print(f" ")
189 + print(f" Connect your MCP client to this URL to start using the tools!")
190 +
191 + return True
192 +
193 + except Exception as e:
194 + print(f"❌ Demo failed: {e}")
195 + import traceback
196 + traceback.print_exc()
197 + return False
198 +
199 +if __name__ == "__main__":
200 + main()
201 +