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

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

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

Synced Nov 22, 22:00 UTC

fix: example

Utkarsh Dixit committed Jul 9, 2025 at 22:59 UTC f71712a80ec879826c19b7e0bebfad5312cb45fa
1 file changed +131 -75
ts/examples/openai/src/mcp.ts
+131 -75
@@ -30,85 +30,101 @@ const openai = new OpenAI({
30 });
31
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: [
33 +const USER_ID = "utkarsh";
34 +
35 +/**
36 + * Get or create MCP server
37 + */
38 +async function getOrCreateMCPServer() {
39 + try {
40 + // Check if MCP server with name already exists
41 + const existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);
42 + console.log(`✅ Found existing MCP server: ${existingServer.id}`);
43 + return existingServer;
44 + } catch (error) {
45 + // Server doesn't exist, create a new one
46 + console.log(`📝 Creating new MCP server: ${MCP_SERVER_NAME}`);
47 +
48 + // Get available auth configs for Gmail
49 + const authConfigsResponse = await composio.authConfigs.list();
50 + const gmailAuthConfig = authConfigsResponse.items.find((config) =>
51 + config.name?.toLowerCase().includes('gmail') ||
52 + config.name?.toLowerCase().includes('google')
53 + );
54 +
55 + if (!gmailAuthConfig) {
56 + throw new Error('No Gmail/Google auth config found. Please create one first.');
57 + }
58 +
59 + // Create MCP server using the new API signature
60 + await composio.mcp.create(
61 + MCP_SERVER_NAME,
62 + [
63 + {
64 + authConfigId: gmailAuthConfig.id,
65 + allowedTools: [
66 + "GMAIL_FETCH_EMAILS"
67 + ]
68 + }
69 + ],
70 {
48 - authConfigId: "ac_MbbEVd0i1TBG", // Replace with your auth config ID
49 - allowedTools: [
50 - "GMAIL_FETCH_EMAILS"
51 - ]
71 + isChatAuth: true
72 }
53 - ],
54 - options: {
55 - // @TODO: Need better name for this
56 - isChatAuth: true
57 - }
58 - });
73 + );
74
60 - // Get the newly created server details
61 - existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);
62 - console.log(`✅ MCP server created: ${existingServer.id}`);
75 + // Get the newly created server details
76 + const newServer = await composio.mcp.getByName(MCP_SERVER_NAME);
77 + console.log(`✅ MCP server created: ${newServer.id}`);
78 + return newServer;
79 + }
80 }
81
65 -console.log("Server details:", existingServer);
66 -
67 -const connectionStatus = await composio.mcp.getUserConnectionStatus({
68 - id: existingServer.id,
69 - userId: USER_ID,
70 -});
71 -
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 -}
82 +/**
83 + * Handle authentication for disconnected toolkits
84 + */
85 +async function handleAuthentication(serverId: string) {
86 + const connectionStatus = await composio.mcp.getUserConnectionStatus(
87 + USER_ID,
88 + serverId
89 + );
90
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 -
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
91 + console.log("Connection status:", connectionStatus);
92 +
93 + const toolkits = connectionStatus.connectedToolkits;
94 +
95 + for (let toolkit of Object.values(toolkits)) {
96 + if (toolkit.type === ConnectionStatus.DISCONNECTED) {
97 + try {
98 + const requiredParams = await composio.mcp.getConnectionParams(
99 + serverId,
100 + toolkit.toolkit
101 + );
102 + console.log("Required params:", requiredParams);
103 +
104 + const authStatus = await composio.mcp.authorize(
105 + serverId,
106 + USER_ID,
107 + toolkit.toolkit
108 + );
109 + console.log("Connection status:", authStatus);
110 +
111 + if (authStatus.redirectUrl) {
112 + console.log(`Please complete the authentication by visiting the following URL: ${authStatus.redirectUrl}`);
113 + console.log("Press 'Enter' once you have completed the authentication.");
114 + await new Promise(resolve => process.stdin.once('data', resolve));
115 + }
116 + } catch (error) {
117 + console.error(`Error handling authentication for ${toolkit.toolkit}:`, error);
118 + }
119 + }
120 }
104 -});
105 -
106 -// console.log("Server URLs for user:", serverUrls);
121 +}
122
108 -// Function to fetch and summarize emails
109 -async function fetchAndSummarizeEmails() {
123 +/**
124 + * Fetch and summarize emails using OpenAI
125 + */
126 +async function fetchAndSummarizeEmails(serverUrls: unknown) {
127 try {
111 - // Use OpenAI to summarize the emails
128 console.log('\n=== Generating Email Summary ===');
129 const completion = await openai.responses.create({
130 model: "gpt-4o-mini",
@@ -121,12 +137,52 @@ async function fetchAndSummarizeEmails() {
137
138 } catch (error) {
139 console.error('Error fetching or summarizing emails:', error);
140 + throw error;
141 }
142 }
143
127 -// Run the email summarization
128 -await fetchAndSummarizeEmails();
144 +/**
145 + * Main function to run the MCP example
146 + */
147 +async function main() {
148 + try {
149 + // Validate environment variables
150 + if (!process.env.COMPOSIO_API_KEY) {
151 + throw new Error('COMPOSIO_API_KEY environment variable is required');
152 + }
153 + if (!process.env.OPENAI_API_KEY) {
154 + throw new Error('OPENAI_API_KEY environment variable is required');
155 + }
156 +
157 + // Get or create MCP server
158 + const server = await getOrCreateMCPServer();
159 + console.log("Server details:", server);
160 +
161 + // Handle authentication for disconnected toolkits
162 + await handleAuthentication(server.id);
163 +
164 + // Get server URLs with user ID using the new API signature
165 + const serverUrls = await composio.mcp.getServer(
166 + server.id,
167 + USER_ID,
168 + {
169 + limitTools: ["GMAIL_FETCH_EMAILS"],
170 + isChatAuth: true
171 + }
172 + );
173 +
174 + // Fetch and summarize emails
175 + await fetchAndSummarizeEmails(serverUrls);
176 +
177 + console.log('\n✅ OpenAI MCP Example completed successfully!');
178 + console.log('\n💡 Note: The MCP server URLs can be used to connect from other MCP-compatible clients');
179 + console.log(`📍 Server ID for future reference: ${server.id}`);
180 +
181 + } catch (error) {
182 + console.error('❌ Error running MCP example:', error);
183 + process.exit(1);
184 + }
185 +}
186
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');
132 -console.log(`📍 Server ID for future reference: ${existingServer.id}`);
187 +// Run the example
188 +main();