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

next
ts 84 lines 2.28 KB
Raw
1 import { openai } from '@ai-sdk/openai';
2 import { createMCPClient } from '@ai-sdk/mcp';
3 import { Composio } from '@composio/core';
4 import { VercelProvider } from '@composio/vercel';
5 import { stepCountIs, streamText } from 'ai';
6
7 // 1. Initialize Composio.
8 const composio = new Composio({
9 provider: new VercelProvider(),
10 });
11
12 // 2. Create an MCP session
13 console.log('🔄 Creating toolrouter session...');
14 const session = await composio.create('default', {
15 toolkits: ['gmail'],
16 manageConnections: true,
17 mcp: true,
18 tools: {
19 gmail: {
20 enable: ['GMAIL_FETCH_EMAILS'],
21 },
22 },
23 });
24
25 const { mcp, sessionId } = session;
26
27 console.log(JSON.stringify(mcp, null, 2));
28 console.log(`✅ Toolrouter session created: ${sessionId}`);
29
30 // 3. Create an MCP client
31 console.log(`🔄 Connecting to MCP Server: ${mcp.url}`);
32 const mcpClient = await createMCPClient({
33 transport: {
34 type: 'http',
35 url: mcp.url,
36 headers: mcp.headers,
37 },
38 });
39
40 // 4. Retrieve tools.
41 console.log(`🔄 Retrieving tools...`);
42 const tools = await mcpClient.tools();
43 console.log(`✅ ${Object.values(tools).length} tools retrieved from MCP client`);
44 console.log(`🔎 Available tools: ${Object.keys(tools).join(', ')}`);
45
46 // 5. Pass tools to Vercel-specific Agent.
47 console.log(`🔄 Executing agent...`);
48 const stream = streamText({
49 model: openai('gpt-5.2'),
50 prompt: `Fetch my latest received email from Gmail and summarize it.`,
51 stopWhen: stepCountIs(10),
52 onStepFinish: step => {
53 if (step.toolCalls.length > 0) {
54 for (let i = 0; i < step.toolCalls.length; i++) {
55 const toolCall = step.toolCalls[i];
56 console.log(`🔧 Executed ${toolCall.toolName}`);
57 const toolResult = step.toolResults?.[i];
58 if (toolResult !== undefined) {
59 console.log(`✅ Result for ${toolCall.toolName}:`, toolResult);
60 }
61 }
62 }
63 },
64 // output: Output.object({
65 // schema: z.object({
66 // subject: z.string(),
67 // bodySummary: z.string(),
68 // date: z.string(),
69 // sender: z.string(),
70 // }),
71 // }),
72 tools,
73 });
74
75 // 6. Execute the Vercel AI-specific Agent.
76 console.log(`🤖 Agent Response:`);
77 for await (const textPart of stream.textStream) {
78 process.stdout.write(textPart);
79 }
80
81 process.stdout.write('\n');
82
83 // 7. Close Vercel AI's MCP client.
84 await mcpClient.close();