Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix: example
Utkarsh Dixitf71712a80ec8
diff --git a/ts/examples/openai/src/mcp.ts b/ts/examples/openai/src/mcp.tsindex 4f461fc3c..15feda4ae 100644--- a/ts/examples/openai/src/mcp.ts+++ b/ts/examples/openai/src/mcp.ts@@ -30,85 +30,101 @@ const openai = new OpenAI({});const MCP_SERVER_NAME = "gmail-readonly-server";-const USER_ID = "utkarsah";--// Check if MCP server with name already exists-let existingServer;-try {- existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);- console.log(`✅ Found existing MCP server: ${existingServer.id}`);-} catch (error) {- // Server doesn't exist, create a new one- console.log(`📝 Creating new MCP server: ${MCP_SERVER_NAME}`);-- const mcpConfig = await composio.mcp.create({- name: MCP_SERVER_NAME,- serverConfig: [+const USER_ID = "utkarsh";++/**+ * Get or create MCP server+ */+async function getOrCreateMCPServer() {+ try {+ // Check if MCP server with name already exists+ const existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);+ console.log(`✅ Found existing MCP server: ${existingServer.id}`);+ return existingServer;+ } catch (error) {+ // Server doesn't exist, create a new one+ console.log(`📝 Creating new MCP server: ${MCP_SERVER_NAME}`);++ // Get available auth configs for Gmail+ const authConfigsResponse = await composio.authConfigs.list();+ const gmailAuthConfig = authConfigsResponse.items.find((config) =>+ config.name?.toLowerCase().includes('gmail') ||+ config.name?.toLowerCase().includes('google')+ );++ if (!gmailAuthConfig) {+ throw new Error('No Gmail/Google auth config found. Please create one first.');+ }++ // Create MCP server using the new API signature+ await composio.mcp.create(+ MCP_SERVER_NAME,+ [+ {+ authConfigId: gmailAuthConfig.id,+ allowedTools: [+ "GMAIL_FETCH_EMAILS"+ ]+ }+ ],{- authConfigId: "ac_MbbEVd0i1TBG", // Replace with your auth config ID- allowedTools: [- "GMAIL_FETCH_EMAILS"- ]+ isChatAuth: true}- ],- options: {- // @TODO: Need better name for this- isChatAuth: true- }- });+ );- // Get the newly created server details- existingServer = await composio.mcp.getByName(MCP_SERVER_NAME);- console.log(`✅ MCP server created: ${existingServer.id}`);+ // Get the newly created server details+ const newServer = await composio.mcp.getByName(MCP_SERVER_NAME);+ console.log(`✅ MCP server created: ${newServer.id}`);+ return newServer;+ }}-console.log("Server details:", existingServer);--const connectionStatus = await composio.mcp.getUserConnectionStatus({- id: existingServer.id,- userId: USER_ID,-});--console.log("Connection status:", connectionStatus);-const toolkits = connectionStatus.connectedToolkits;-for (let toolkit of Object.values(toolkits)) {- if(toolkit.type === ConnectionStatus.DISCONNECTED) {- const requiredParams = await composio.mcp.getConnectionParams({id: existingServer.id, toolkit: toolkit.toolkit});- console.log("Required params:", requiredParams);- const connectionStatus = await composio.mcp.authorize({id: existingServer.id, userId: USER_ID, toolkit: toolkit.toolkit});- console.log("Connection status:", connectionStatus);-if (connectionStatus.redirectUrl) {- console.log(`Please complete the authentication by visiting the following URL: ${connectionStatus.redirectUrl}`);- console.log("Press 'Enter' once you have completed the authentication.");- await new Promise(resolve => process.stdin.once('data', resolve));-}-}-}+/**+ * Handle authentication for disconnected toolkits+ */+async function handleAuthentication(serverId: string) {+ const connectionStatus = await composio.mcp.getUserConnectionStatus(+ USER_ID,+ serverId+ );-// console.log(`✅ MCP server created: ${mcpConfig.id}`);-// console.log(`🔧 Available toolkits: ${mcpConfig.toolkits.join(', ')}`);--// // Get server URLs with user ID (using convenience method)-// const serverUrls = await mcpConfig.getServer({-// userId: "utkarsh" // Replace with your user ID-// });--// Alternative: You can also use the standalone method to get URLs later-const serverUrls = await composio.mcp.getServer({- id: existingServer.id,- userId: USER_ID,- options: {- limitTools: ["GMAIL_FETCH_EMAILS"],- isChatAuth: true+ console.log("Connection status:", connectionStatus);++ const toolkits = connectionStatus.connectedToolkits;++ for (let toolkit of Object.values(toolkits)) {+ if (toolkit.type === ConnectionStatus.DISCONNECTED) {+ try {+ const requiredParams = await composio.mcp.getConnectionParams(+ serverId,+ toolkit.toolkit+ );+ console.log("Required params:", requiredParams);++ const authStatus = await composio.mcp.authorize(+ serverId,+ USER_ID,+ toolkit.toolkit+ );+ console.log("Connection status:", authStatus);++ if (authStatus.redirectUrl) {+ console.log(`Please complete the authentication by visiting the following URL: ${authStatus.redirectUrl}`);+ console.log("Press 'Enter' once you have completed the authentication.");+ await new Promise(resolve => process.stdin.once('data', resolve));+ }+ } catch (error) {+ console.error(`Error handling authentication for ${toolkit.toolkit}:`, error);+ }+ }}-});--// console.log("Server URLs for user:", serverUrls);+}-// Function to fetch and summarize emails-async function fetchAndSummarizeEmails() {+/**+ * Fetch and summarize emails using OpenAI+ */+async function fetchAndSummarizeEmails(serverUrls: unknown) {try {- // Use OpenAI to summarize the emailsconsole.log('\n=== Generating Email Summary ===');const completion = await openai.responses.create({model: "gpt-4o-mini",@@ -121,12 +137,52 @@ async function fetchAndSummarizeEmails() {} catch (error) {console.error('Error fetching or summarizing emails:', error);+ throw error;}}-// Run the email summarization-await fetchAndSummarizeEmails();+/**+ * Main function to run the MCP example+ */+async function main() {+ try {+ // Validate environment variables+ if (!process.env.COMPOSIO_API_KEY) {+ throw new Error('COMPOSIO_API_KEY environment variable is required');+ }+ if (!process.env.OPENAI_API_KEY) {+ throw new Error('OPENAI_API_KEY environment variable is required');+ }++ // Get or create MCP server+ const server = await getOrCreateMCPServer();+ console.log("Server details:", server);++ // Handle authentication for disconnected toolkits+ await handleAuthentication(server.id);++ // Get server URLs with user ID using the new API signature+ const serverUrls = await composio.mcp.getServer(+ server.id,+ USER_ID,+ {+ limitTools: ["GMAIL_FETCH_EMAILS"],+ isChatAuth: true+ }+ );++ // Fetch and summarize emails+ await fetchAndSummarizeEmails(serverUrls);++ console.log('\n✅ OpenAI MCP Example completed successfully!');+ console.log('\n💡 Note: The MCP server URLs can be used to connect from other MCP-compatible clients');+ console.log(`📍 Server ID for future reference: ${server.id}`);++ } catch (error) {+ console.error('❌ Error running MCP example:', error);+ process.exit(1);+ }+}-console.log('\n✅ OpenAI MCP Example completed successfully!');-console.log('\n💡 Note: The MCP server URLs can be used to connect from other MCP-compatible clients');-console.log(`📍 Server ID for future reference: ${existingServer.id}`);+// Run the example+main();