@devries-cameron20 / composio Mirror · read-only
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 21, 06:00 UTC

next
ts 189 lines 4.85 KB
Raw
1 /**
2 * E2E test worker for Tool Router AI pattern with Composio.
3 * Tests MCP session creation, tool retrieval, and Vercel AI SDK integration
4 * in the Cloudflare Workers runtime environment.
5 */
6 import { createOpenAI } from '@ai-sdk/openai';
7 import { createMCPClient } from '@ai-sdk/mcp';
8 import { Composio } from '@composio/core';
9 import { VercelProvider } from '@composio/vercel';
10 import { generateText, Output, stepCountIs } from 'ai';
11 import { Hono } from 'hono';
12 import { z } from 'zod/v4';
13
14 type Bindings = {
15 COMPOSIO_API_KEY: string;
16 COMPOSIO_BASE_URL: string;
17 OPENAI_API_KEY: string;
18 };
19
20 const app = new Hono<{ Bindings: Bindings }>();
21
22 const hackerNewsUserOutputSchema = z
23 .union([
24 z.object({
25 username: z.string().optional(),
26 karma: z.number(),
27 }),
28 z.object({
29 data: z.object({
30 username: z.string().optional(),
31 karma: z.number(),
32 }),
33 }),
34 ])
35 .transform(output => ('data' in output ? output.data : output));
36
37 /**
38 * Default route - lists available test endpoints
39 */
40 app.get('/', c => {
41 return c.json({
42 message: 'Tool Router AI E2E Test Worker',
43 endpoints: ['/test/mcp-client', '/test/agent'],
44 });
45 });
46
47 /**
48 * Test: MCP Client Connection
49 * Tests that we can connect to the MCP server using @ai-sdk/mcp
50 */
51 app.get('/test/mcp-client', async c => {
52 const composio = new Composio({
53 apiKey: c.env.COMPOSIO_API_KEY,
54 baseURL: c.env.COMPOSIO_BASE_URL,
55 provider: new VercelProvider(),
56 });
57
58 const session = await composio.create('default', {
59 toolkits: ['hackernews'],
60 manageConnections: true,
61 tools: {
62 hackernews: {
63 enable: ['HACKERNEWS_GET_USER'],
64 },
65 },
66 mcp: true,
67 });
68
69 const { mcp } = session;
70
71 await createMCPClient({
72 transport: {
73 type: 'http',
74 url: mcp.url,
75 headers: mcp.headers,
76 redirect: 'follow',
77 fetch: (input, init) => fetch(input, init),
78 },
79 });
80 // Intentionally do not close the HTTP MCP client here: in workerd, @ai-sdk/mcp
81 // aborts the pending stream and Vitest reports it as an unhandled rejection.
82
83 return c.json({
84 message: 'MCP client connected successfully',
85 mcpUrl: mcp.url,
86 });
87 });
88
89 /**
90 * Test: Agent Execution
91 * Tests the full workflow: create session, get tools, run agent with generateText.
92 *
93 * Note: this takes ~40s locally.
94 */
95 app.get('/test/agent', async c => {
96 const composio = new Composio({
97 apiKey: c.env.COMPOSIO_API_KEY,
98 baseURL: c.env.COMPOSIO_BASE_URL,
99 provider: new VercelProvider(),
100 });
101
102 const session = await composio.create('default', {
103 toolkits: ['hackernews'],
104 manageConnections: true,
105 preload: { tools: ['HACKERNEWS_GET_USER'] },
106 tools: {
107 hackernews: {
108 enable: ['HACKERNEWS_GET_USER'],
109 },
110 },
111 mcp: true,
112 });
113
114 const { mcp, sessionId } = session;
115
116 const mcpClient = await createMCPClient({
117 transport: {
118 type: 'http',
119 url: mcp.url,
120 headers: mcp.headers,
121 redirect: 'follow',
122 fetch: (input, init) => fetch(input, init),
123 },
124 });
125 // Intentionally do not close the HTTP MCP client here: in workerd, @ai-sdk/mcp
126 // aborts the pending stream and Vitest reports it as an unhandled rejection.
127
128 const tools = await mcpClient.tools({
129 schemas: {
130 HACKERNEWS_GET_USER: {
131 inputSchema: z.object({
132 username: z.string(),
133 }),
134 outputSchema: hackerNewsUserOutputSchema,
135 },
136 },
137 });
138 const openai = createOpenAI({ apiKey: c.env.OPENAI_API_KEY });
139
140 const result = await generateText({
141 model: openai('gpt-5.5'),
142 prompt: `Look up the HackerNews user "pg" with HACKERNEWS_GET_USER, then return the exact karma value from that tool result.`,
143 output: Output.object({
144 schema: z.object({
145 karma: z.number(),
146 }),
147 }),
148 stopWhen: stepCountIs(10),
149 tools,
150 });
151
152 if (result.finishReason !== 'stop') {
153 const responseBodySchema = z.object({ incomplete_details: z.unknown() });
154 console.error(
155 'Agent step diagnostics',
156 JSON.stringify(
157 result.steps.map(step => ({
158 finishReason: step.finishReason,
159 responseId: step.response.id,
160 incompleteDetails: responseBodySchema.safeParse(step.response.body).data
161 ?.incomplete_details,
162 usage: step.usage,
163 toolCalls: step.toolCalls.map(({ toolName, input }) => ({ toolName, input })),
164 }))
165 )
166 );
167 }
168
169 const toolCalls = result.steps.flatMap(step =>
170 step.toolCalls.map(toolCall => ({ toolName: toolCall.toolName }))
171 );
172 const toolResults = result.steps.flatMap(step =>
173 step.toolResults.map(toolResult => ({
174 toolName: toolResult.toolName,
175 output: toolResult.output,
176 }))
177 );
178
179 return c.json({
180 message: 'Agent executed successfully',
181 sessionId,
182 toolCount: Object.keys(tools).length,
183 toolCalls,
184 toolResults,
185 response: result.output,
186 });
187 });
188
189 export default app;