1
+/**
2
+ * Every route the fake backend answers.
3
+ *
4
+ * A route named after a `@composio/client` operation (`typed: true`) answers
5
+ * with the shape that operation's response schema describes; the contract test
6
+ * decodes each one with the client's own schema.
7
+ */
8
+
9
+import { z } from 'zod';
10
+import { errorEnvelope } from './faults';
11
+import { badRequest, notFound, singlePage, type Route, type RouteContext } from './route';
12
+import {
13
+ CONSUMER_PROJECT,
14
+ CONSUMER_USER_ID,
15
+ MEMBER,
16
+ SEEDED_AT,
17
+ SEEDED_EXPIRY,
18
+ type AuthConfig,
19
+ type Connection,
20
+ type Release,
21
+ type SeededProject,
22
+ type SeededTool,
23
+ type SeededToolkit,
24
+ type World,
25
+} from './world';
26
+
27
+const LOGO = 'https://logos.composio.test/toolkit.svg';
28
+
29
+// --- request bodies -----------------------------------------------------------
30
+
31
+const SessionCreateBody = z.looseObject({ user_id: z.string() });
32
+const SearchBody = z.looseObject({
33
+ queries: z.array(z.looseObject({ use_case: z.string() })).optional(),
34
+});
35
+const ExecuteBody = z.looseObject({
36
+ tool_slug: z.string(),
37
+ arguments: z.record(z.string(), z.unknown()).optional(),
38
+ account: z.string().optional(),
39
+});
40
+const ExecuteMetaBody = z.looseObject({
41
+ slug: z.string(),
42
+ arguments: z.record(z.string(), z.unknown()).optional(),
43
+});
44
+const SessionLinkBody = z.looseObject({ toolkit: z.string(), alias: z.string().optional() });
45
+const LinkCreateBody = z.looseObject({
46
+ auth_config_id: z.string(),
47
+ user_id: z.string(),
48
+ alias: z.string().optional(),
49
+});
50
+const DirectExecuteBody = z.looseObject({
51
+ user_id: z.string().optional(),
52
+ arguments: z.record(z.string(), z.unknown()).optional(),
53
+ connected_account_id: z.string().optional(),
54
+});
55
+const ApiKeyCreateBody = z.looseObject({ name: z.string() });
56
+const TrpcBody = z.object({ json: z.record(z.string(), z.unknown()) });
57
+
58
+// --- response builders --------------------------------------------------------
59
+
60
+const projectDetails = (project: SeededProject, world: World) => ({
61
+ auto_id: project.autoId,
62
+ id: project.uuid,
63
+ org_id: project.orgId,
64
+ name: project.name,
65
+ email: `${project.name}@projects.composio.test`,
66
+ nano_id: project.nanoId,
67
+ created_at: SEEDED_AT,
68
+ updated_at: SEEDED_AT,
69
+ webhook_url: null,
70
+ event_webhook_url: null,
71
+ webhook_secret: null,
72
+ triggers_enabled: true,
73
+ last_subscribed_at: null,
74
+ deleted: false,
75
+ is_new_webhook: true,
76
+ webhook_version: 'V3',
77
+ org: { id: world.org.id, name: world.org.name, plan: world.org.plan },
78
+});
79
+
80
+const toolkitListItem = (toolkit: SeededToolkit, world: World) => ({
81
+ slug: toolkit.slug,
82
+ name: toolkit.name,
83
+ type: 'native',
84
+ app: toolkit.slug,
85
+ toolkit_type: 'api',
86
+ is_local_toolkit: false,
87
+ auth_schemes: toolkit.noAuth ? [] : ['OAUTH2'],
88
+ composio_managed_auth_schemes: toolkit.noAuth ? [] : ['OAUTH2'],
89
+ no_auth: toolkit.noAuth,
90
+ deprecated: { toolkitId: `tk_${toolkit.slug}` },
91
+ meta: {
92
+ created_at: SEEDED_AT,
93
+ updated_at: SEEDED_AT,
94
+ description: toolkit.description,
95
+ logo: LOGO,
96
+ categories: [],
97
+ triggers_count: 0,
98
+ tools_count: world.tools.filter(tool => tool.toolkit === toolkit.slug).length,
99
+ version: toolkit.version,
100
+ available_versions: [toolkit.version],
101
+ },
102
+});
103
+
104
+const toolkitDetails = (toolkit: SeededToolkit, world: World) => ({
105
+ slug: toolkit.slug,
106
+ name: toolkit.name,
107
+ type: 'native',
108
+ enabled: true,
109
+ no_auth: toolkit.noAuth,
110
+ composio_managed_auth_schemes: toolkit.noAuth ? [] : ['OAUTH2'],
111
+ composio_managed_auth: toolkit.noAuth
112
+ ? []
113
+ : [
114
+ {
115
+ managed_app_id: `ma_${toolkit.slug}`,
116
+ is_default: true,
117
+ mode: 'OAUTH2',
118
+ scopes: { available: [] },
119
+ },
120
+ ],
121
+ is_local_toolkit: false,
122
+ auth_config_details: toolkit.noAuth
123
+ ? []
124
+ : [
125
+ {
126
+ mode: 'OAUTH2',
127
+ name: 'OAuth 2.0',
128
+ required_scopes: [],
129
+ fields: {
130
+ auth_config_creation: { required: [], optional: [] },
131
+ connected_account_initiation: { required: [], optional: [] },
132
+ },
133
+ },
134
+ ],
135
+ meta: {
136
+ created_at: SEEDED_AT,
137
+ updated_at: SEEDED_AT,
138
+ description: toolkit.description,
139
+ logo: LOGO,
140
+ categories: [],
141
+ triggers_count: 0,
142
+ tools_count: world.tools.filter(tool => tool.toolkit === toolkit.slug).length,
143
+ version: toolkit.version,
144
+ available_versions: [toolkit.version],
145
+ },
146
+ deprecated: { toolkitId: `tk_${toolkit.slug}`, rawProxyInfoByAuthSchemes: [] },
147
+});
148
+
149
+const toolDetails = (tool: SeededTool, world: World) => {
150
+ const toolkit = world.findToolkit(tool.toolkit);
151
+ const version = toolkit?.version ?? 'latest';
152
+ return {
153
+ slug: tool.slug,
154
+ name: tool.name,
155
+ description: tool.description,
156
+ toolkit: { slug: tool.toolkit, name: toolkit?.name ?? tool.toolkit, logo: LOGO },
157
+ input_parameters: tool.inputParameters,
158
+ no_auth: toolkit?.noAuth ?? false,
159
+ available_versions: [version],
160
+ version,
161
+ output_parameters: { type: 'object', properties: {} },
162
+ scopes: [],
163
+ scope_requirements: null,
164
+ tags: [],
165
+ is_deprecated: false,
166
+ deprecated: {
167
+ displayName: tool.name,
168
+ version,
169
+ available_versions: [version],
170
+ is_deprecated: false,
171
+ toolkit: { logo: LOGO },
172
+ },
173
+ };
174
+};
175
+
176
+const connectedAccount = (connection: Connection, urls: RouteContext['urls']) => {
177
+ if (connection.status === 'ACTIVE') connection.reportedActive = true;
178
+ return {
179
+ toolkit: { slug: connection.toolkit },
180
+ auth_config: {
181
+ id: connection.authConfigId,
182
+ auth_scheme: 'OAUTH2',
183
+ is_composio_managed: true,
184
+ is_disabled: false,
185
+ },
186
+ id: connection.id,
187
+ word_id: connection.wordId,
188
+ alias: connection.alias,
189
+ user_id: connection.userId,
190
+ status: connection.status,
191
+ created_at: SEEDED_AT,
192
+ updated_at: SEEDED_AT,
193
+ state:
194
+ connection.status === 'ACTIVE'
195
+ ? {
196
+ authScheme: 'OAUTH2',
197
+ val: { status: 'ACTIVE', access_token: 'REDACTED', token_type: 'Bearer' },
198
+ }
199
+ : {
200
+ authScheme: 'OAUTH2',
201
+ val: { status: 'INITIATED', redirectUrl: redirectUrl(urls, connection) },
202
+ },
203
+ data: {},
204
+ params: {},
205
+ status_reason: null,
206
+ is_disabled: false,
207
+ test_request_endpoint: '',
208
+ deprecated: { labels: [], uuid: `00000000-0000-4000-8000-${connection.id.padStart(12, '0')}` },
209
+ };
210
+};
211
+
212
+const authConfigItem = (authConfig: AuthConfig, world: World) => ({
213
+ id: authConfig.id,
214
+ uuid: authConfig.uuid,
215
+ type: 'default',
216
+ toolkit: { slug: authConfig.toolkit, logo: LOGO },
217
+ name: authConfig.name,
218
+ auth_scheme: 'OAUTH2',
219
+ is_composio_managed: true,
220
+ status: 'ENABLED',
221
+ created_by: MEMBER.id,
222
+ created_at: SEEDED_AT,
223
+ last_updated_at: SEEDED_AT,
224
+ no_of_connections: world.connections.filter(c => c.authConfigId === authConfig.id).length,
225
+ tool_access_config: {
226
+ tools_for_connected_account_creation: [],
227
+ tools_available_for_execution: [],
228
+ },
229
+});
230
+
231
+const redirectUrl = (urls: RouteContext['urls'], connection: Connection) =>
232
+ `${urls.backend}/api/v3/s/${connection.id}`;
233
+
234
+const noActiveConnection = (toolkit: string) => ({
235
+ status: 400,
236
+ json: errorEnvelope({
237
+ status: 400,
238
+ code: 4302,
239
+ slug: 'ToolRouterV2_NoActiveConnection',
240
+ message: `No active connection found for toolkit ${toolkit}`,
241
+ suggestedFix: `Connect ${toolkit} before executing this tool`,
242
+ }),
243
+});
244
+
245
+const unknownTool = (slug: string) => notFound(`Tool ${slug} not found`, 'Tool_ToolNotFound');
246
+
247
+/** The session named in the path, with the project and user it was created for. */
248
+const sessionOf = (context: RouteContext) =>
249
+ context.world.toolRouterSessions.find(session => session.id === context.params.sessionId);
250
+
251
+const unknownSession = (context: RouteContext) =>
252
+ notFound(
253
+ `Tool router session ${context.params.sessionId} not found`,
254
+ 'ToolRouterV2_SessionNotFound'
255
+ );
256
+
257
+/**
258
+ * Runs a tool for a user on a project: the connection check and the tool's
259
+ * canned answer. Shared by the session, Dashboard, and direct execute routes.
260
+ */
261
+const runTool = (
262
+ world: World,
263
+ params: { projectLabel: string; userId: string; slug: string; args: Record<string, unknown> }
264
+):
265
+ | { kind: 'unknown-tool' }
266
+ | { kind: 'not-connected'; toolkit: string }
267
+ | { kind: 'ran'; data: Record<string, unknown>; logId: string } => {
268
+ const tool = world.findTool(params.slug);
269
+ if (!tool) return { kind: 'unknown-tool' };
270
+ const toolkit = world.findToolkit(tool.toolkit);
271
+ if (
272
+ !toolkit?.noAuth &&
273
+ !world.reportActiveConnection(params.projectLabel, params.userId, tool.toolkit)
274
+ ) {
275
+ return { kind: 'not-connected', toolkit: tool.toolkit };
276
+ }
277
+ return { kind: 'ran', data: tool.respond(params.args), logId: world.nextLogId() };
278
+};
279
+
280
+const searchResponse = (
281
+ context: RouteContext,
282
+ session: { id: string; projectLabel: string; userId: string },
283
+ useCases: ReadonlyArray<string>
284
+) => {
285
+ const { world } = context;
286
+ const matches = useCases.map(useCase => {
287
+ const words = useCase
288
+ .toLowerCase()
289
+ .split(/[^a-z0-9]+/)
290
+ .filter(word => word.length > 2);
291
+ const tools = world.tools.filter(tool => {
292
+ const haystack =
293
+ `${tool.slug} ${tool.name} ${tool.description} ${tool.toolkit}`.toLowerCase();
294
+ return words.some(word => haystack.includes(word));
295
+ });
296
+ // Toolkit names outrank incidental word overlap ("send" matches Slack and Gmail).
297
+ const named = tools.filter(tool => words.includes(tool.toolkit));
298
+ return { useCase, tools: named.length > 0 ? named : tools };
299
+ });
300
+ const toolkits = [...new Set(matches.flatMap(match => match.tools.map(tool => tool.toolkit)))];
301
+ const allTools = [...new Set(matches.flatMap(match => match.tools))];
302
+
303
+ return {
304
+ success: true,
305
+ error: null,
306
+ results: matches.map((match, index) => ({
307
+ index: index + 1,
308
+ use_case: match.useCase,
309
+ execution_guidance: 'Execute the primary tool with the documented arguments.',
310
+ primary_tool_slugs: match.tools.slice(0, 1).map(tool => tool.slug),
311
+ related_tool_slugs: match.tools.slice(1).map(tool => tool.slug),
312
+ toolkits: [...new Set(match.tools.map(tool => tool.toolkit))],
313
+ })),
314
+ toolkit_connection_statuses: toolkits.map(slug => {
315
+ const toolkit = world.findToolkit(slug);
316
+ const connection = world.reportActiveConnection(session.projectLabel, session.userId, slug);
317
+ const connected = toolkit?.noAuth === true || connection !== undefined;
318
+ return {
319
+ toolkit: slug,
320
+ description: toolkit?.description ?? '',
321
+ has_active_connection: connected,
322
+ status_message: connected
323
+ ? `${slug} is connected`
324
+ : `No active connection for ${slug}. Initiate a connection before executing its tools.`,
325
+ };
326
+ }),
327
+ tool_schemas: Object.fromEntries(
328
+ allTools.map(tool => [
329
+ tool.slug,
330
+ {
331
+ tool_slug: tool.slug,
332
+ toolkit: tool.toolkit,
333
+ description: tool.description,
334
+ input_schema: tool.inputParameters,
335
+ hasFullSchema: true,
336
+ },
337
+ ])
338
+ ),
339
+ time_info: {
340
+ current_time_utc: SEEDED_AT,
341
+ current_time_utc_epoch_seconds: Date.parse(SEEDED_AT) / 1000,
342
+ message: 'Fixed time of the fake backend.',
343
+ },
344
+ session: { id: session.id, generate_id: false, instructions: 'Reuse this session id.' },
345
+ next_steps_guidance: ['Execute the primary tool slug for each use case.'],
346
+ };
347
+};
348
+
349
+// --- routes -------------------------------------------------------------------
350
+
351
+const backend = (route: Omit<Route, 'role'>): Route => ({ ...route, role: 'backend' });
352
+
353
+const ACCOUNT_ROUTES: ReadonlyArray<Route> = [
354
+ backend({
355
+ name: 'auth.session.retrieveInfo',
356
+ method: 'GET',
357
+ path: '/api/:v/auth/session/info',
358
+ typed: true,
359
+ auth: 'user',
360
+ handle: ({ world, project }) => ({
361
+ json: {
362
+ // A user key belongs to no project, so the org's default developer
363
+ // project is reported, never the consumer project: a command that
364
+ // reuses this id instead of resolving the consumer project shows up in
365
+ // the journal as acting on the wrong project.
366
+ project: projectDetails(project ?? world.defaultProject, world),
367
+ api_key: null,
368
+ org_member: {
369
+ id: world.member.id,
370
+ email: world.member.email,
371
+ name: world.member.name,
372
+ role: world.member.role,
373
+ metadata: {},
374
+ },
375
+ },
376
+ }),
377
+ }),
378
+ backend({
379
+ name: 'org.list',
380
+ method: 'GET',
381
+ path: '/api/:v/org/list',
382
+ typed: true,
383
+ auth: 'user',
384
+ handle: ({ world }) => ({
385
+ json: {
386
+ organizations: world.organizations.map(org => ({
387
+ id: org.id,
388
+ name: org.name,
389
+ created_at: SEEDED_AT,
390
+ updated_at: SEEDED_AT,
391
+ })),
392
+ next_cursor: null,
393
+ total_pages: 1,
394
+ current_page: 1,
395
+ total_items: world.organizations.length,
396
+ },
397
+ }),
398
+ }),
399
+ backend({
400
+ name: 'org.project.list',
401
+ method: 'GET',
402
+ path: '/api/:v/org/project/list',
403
+ typed: true,
404
+ auth: 'user',
405
+ handle: ({ world, identity }) => {
406
+ const projects = world.projects.filter(
407
+ project =>
408
+ project.kind === 'developer' && project.orgId === (identity.orgId ?? world.org.id)
409
+ );
410
+ return {
411
+ json: {
412
+ data: projects.map(project => ({
413
+ id: project.nanoId,
414
+ org_id: project.orgId,
415
+ name: project.name,
416
+ email: `${project.name}@projects.composio.test`,
417
+ created_at: SEEDED_AT,
418
+ updated_at: SEEDED_AT,
419
+ webhook_url: null,
420
+ event_webhook_url: null,
421
+ webhook_secret: null,
422
+ triggers_enabled: true,
423
+ last_subscribed_at: null,
424
+ is_new_webhook: true,
425
+ webhook_version: 'V3',
426
+ deleted: false,
427
+ })),
428
+ next_cursor: null,
429
+ total_pages: 1,
430
+ current_page: 1,
431
+ total_items: projects.length,
432
+ },
433
+ };
434
+ },
435
+ }),
436
+ backend({
437
+ name: 'org.project.apiKeys.create',
438
+ method: 'POST',
439
+ path: '/api/:v/org/project/:projectId/api_keys/create',
440
+ typed: false,
441
+ auth: 'user',
442
+ handle: ({ world, params, body }) => {
443
+ const project = world.findProject(params.projectId);
444
+ if (!project) return notFound(`Project ${params.projectId} not found`, 'Project_NotFound');
445
+ const { name } = ApiKeyCreateBody.parse(body);
446
+ const key = world.mintProjectKey(project.label, name);
447
+ return {
448
+ json: { id: `key_${world.mintedProjectKeys.length}`, name, key, created_at: SEEDED_AT },
449
+ acted: { project: project.label },
450
+ };
451
+ },
452
+ }),
453
+ backend({
454
+ name: '_internal.org.consumer.project.resolve',
455
+ method: 'POST',
456
+ path: '/api/:v/org/consumer/project/resolve',
457
+ typed: true,
458
+ auth: 'user',
459
+ handle: ({ identity }) => ({
460
+ json: {
461
+ project_id: CONSUMER_PROJECT.uuid,
462
+ project_nano_id: CONSUMER_PROJECT.nanoId,
463
+ project_name: CONSUMER_PROJECT.name,
464
+ org_id: identity.orgId ?? CONSUMER_PROJECT.orgId,
465
+ project_type: 'CONSUMER',
466
+ config: {
467
+ consumer_experience_enabled: true,
468
+ enhanced_controls: false,
469
+ enable_instant: false,
470
+ },
471
+ consumer_user_id: CONSUMER_USER_ID,
472
+ user_id: MEMBER.id,
473
+ },
474
+ acted: { project: CONSUMER_PROJECT.label, userId: CONSUMER_USER_ID },
475
+ }),
476
+ }),
477
+ backend({
478
+ name: '_internal.org.consumer.listConnectedToolkits',
479
+ method: 'GET',
480
+ path: '/api/:v/org/consumer/connected_toolkits',
481
+ typed: true,
482
+ auth: 'user',
483
+ handle: ({ world, query }) => {
484
+ const userId = query.get('user_id') ?? CONSUMER_USER_ID;
485
+ const toolkits = world.connections
486
+ .filter(
487
+ connection =>
488
+ connection.projectLabel === CONSUMER_PROJECT.label &&
489
+ connection.userId === userId &&
490
+ connection.status === 'ACTIVE'
491
+ )
492
+ .map(connection => connection.toolkit);
493
+ return {
494
+ json: { toolkits: [...new Set(toolkits)] },
495
+ acted: { project: CONSUMER_PROJECT.label, userId },
496
+ };
497
+ },
498
+ }),
499
+ backend({
500
+ name: '_internal.org.consumer.retrieveConfig',
501
+ method: 'GET',
502
+ path: '/api/:v/org/consumer/config',
503
+ typed: true,
504
+ auth: 'user',
505
+ handle: ({ world, identity }) => ({
506
+ json: {
507
+ org_id: identity.orgId ?? world.org.id,
508
+ consumer_experience_enabled: true,
509
+ enhanced_controls: false,
510
+ },
511
+ }),
512
+ }),
513
+ backend({
514
+ name: '_internal.consumer.permissions.resolve',
515
+ method: 'POST',
516
+ path: '/api/:v/consumer/permissions/resolve',
517
+ typed: true,
518
+ auth: 'user',
519
+ handle: () => ({
520
+ json: { experimental: { permissions: { default: 'allow_all', overrides: {} } } },
521
+ }),
522
+ }),
523
+];
524
+
525
+const LOGIN_ROUTES: ReadonlyArray<Route> = [
526
+ backend({
527
+ name: '_internal.cli.createSession',
528
+ method: 'POST',
529
+ path: '/api/:v/cli/create-session',
530
+ typed: true,
531
+ auth: 'none',
532
+ handle: ({ world }) => {
533
+ const session = world.createLoginSession();
534
+ return {
535
+ json: {
536
+ id: session.id,
537
+ code: session.code,
538
+ expiresAt: SEEDED_EXPIRY,
539
+ status: session.status,
540
+ scope: 'user',
541
+ },
542
+ };
543
+ },
544
+ }),
545
+ backend({
546
+ name: '_internal.cli.getSession',
547
+ method: 'GET',
548
+ path: '/api/:v/cli/get-session',
549
+ typed: true,
550
+ auth: 'none',
551
+ handle: ({ world, query }) => {
552
+ const reference = query.get('id') ?? query.get('code') ?? '';
553
+ const session = world.loginSessions.find(s => s.id === reference || s.code === reference);
554
+ if (!session) return notFound(`CLI session ${reference} not found`, 'Cli_SessionNotFound');
555
+ const linked = session.status === 'linked';
556
+ if (linked) session.reportedLinked = true;
557
+ return {
558
+ json: {
559
+ id: session.id,
560
+ code: session.code,
561
+ status: session.status,
562
+ expiresAt: SEEDED_EXPIRY,
563
+ account: linked
564
+ ? { id: world.member.id, email: world.member.email, name: world.member.name }
565
+ : null,
566
+ api_key: linked ? world.userApiKey : null,
567
+ scope: 'user',
568
+ },
569
+ };
570
+ },
571
+ }),
572
+ backend({
573
+ // The page a link's `redirect_url` points at. Whoever opens it is the
574
+ // account's owner at the consent screen, and opening it is their approval.
575
+ name: 'connectedAccounts.authorizationPage',
576
+ method: 'GET',
577
+ path: '/api/:v/s/:id',
578
+ typed: false,
579
+ auth: 'none',
580
+ handle: ({ world, params }) =>
581
+ world.authorizeConnection(params.id ?? '')
582
+ ? { text: 'Authorized. You can close this tab.' }
583
+ : notFound(`No pending authorization ${params.id}`, 'ConnectedAccount_NotFound'),
584
+ }),
585
+ backend({
586
+ name: 'cli.analytics',
587
+ method: 'POST',
588
+ path: '/api/:v/cli/analytics',
589
+ typed: false,
590
+ auth: 'none',
591
+ handle: () => ({ status: 204 }),
592
+ }),
593
+];
594
+
595
+const CATALOG_ROUTES: ReadonlyArray<Route> = [
596
+ backend({
597
+ name: 'toolkits.list',
598
+ method: 'GET',
599
+ path: '/api/:v/toolkits',
600
+ typed: true,
601
+ auth: 'key',
602
+ handle: ({ world, query }) => {
603
+ const search = query.get('search')?.toLowerCase();
604
+ const items = world.toolkits
605
+ .filter(toolkit => !search || toolkit.slug.startsWith(search))
606
+ .map(toolkit => toolkitListItem(toolkit, world));
607
+ return { json: singlePage(items) };
608
+ },
609
+ }),
610
+ backend({
611
+ name: 'toolkits.retrieve',
612
+ method: 'GET',
613
+ path: '/api/:v/toolkits/:slug',
614
+ typed: true,
615
+ auth: 'key',
616
+ handle: ({ world, params }) => {
617
+ const toolkit = world.findToolkit(params.slug ?? '');
618
+ return toolkit
619
+ ? { json: toolkitDetails(toolkit, world) }
620
+ : notFound(`Toolkit ${params.slug} not found`, 'Toolkit_NotFound');
621
+ },
622
+ }),
623
+ backend({
624
+ name: 'tools.list',
625
+ method: 'GET',
626
+ path: '/api/:v/tools',
627
+ typed: true,
628
+ auth: 'key',
629
+ handle: ({ world, query }) => {
630
+ const toolkit = query.get('toolkit_slug')?.toLowerCase();
631
+ const slugs = query.get('tool_slugs')?.toUpperCase().split(',');
632
+ const items = world.tools
633
+ .filter(tool => !toolkit || tool.toolkit === toolkit)
634
+ .filter(tool => !slugs || slugs.includes(tool.slug))
635
+ .map(tool => toolDetails(tool, world));
636
+ return { json: singlePage(items) };
637
+ },
638
+ }),
639
+ backend({
640
+ name: 'tools.getLatestVersion',
641
+ method: 'GET',
642
+ path: '/api/:v/tools/:slug/get_latest_version',
643
+ typed: false,
644
+ auth: 'key',
645
+ handle: ({ world, params }) => {
646
+ const tool = world.findTool(params.slug ?? '');
647
+ if (!tool) return unknownTool(params.slug ?? '');
648
+ return {
649
+ json: {
650
+ slug: tool.slug,
651
+ toolkit: tool.toolkit,
652
+ version: world.findToolkit(tool.toolkit)?.version ?? 'latest',
653
+ },
654
+ };
655
+ },
656
+ }),
657
+ backend({
658
+ name: 'tools.retrieve',
659
+ method: 'GET',
660
+ path: '/api/:v/tools/:slug',
661
+ typed: true,
662
+ auth: 'key',
663
+ handle: ({ world, params }) => {
664
+ const tool = world.findTool(params.slug ?? '');
665
+ return tool ? { json: toolDetails(tool, world) } : unknownTool(params.slug ?? '');
666
+ },
667
+ }),
668
+];
669
+
670
+const SESSION_ROUTES: ReadonlyArray<Route> = [
671
+ backend({
672
+ name: 'toolRouter.session.create',
673
+ method: 'POST',
674
+ path: '/api/:v/tool_router/session',
675
+ typed: true,
676
+ auth: 'project',
677
+ handle: ({ world, body, project, urls }) => {
678
+ const { user_id: userId } = SessionCreateBody.parse(body);
679
+ const session = world.createToolRouterSession(project!.label, userId);
680
+ return {
681
+ status: 201,
682
+ json: {
683
+ session_id: session.id,
684
+ mcp: { type: 'http', url: `${urls.backend}/tool_router/${session.id}/mcp` },
685
+ tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MULTI_EXECUTE_TOOL'],
686
+ config: {
687
+ user_id: userId,
688
+ instant: false,
689
+ preload: { tools: [] },
690
+ search: { enable: true },
691
+ execute: { enable_multi_execute: true },
692
+ },
693
+ config_version: 1,
694
+ },
695
+ acted: { project: project!.label, userId },
696
+ };
697
+ },
698
+ }),
699
+ backend({
700
+ name: 'toolRouter.session.search',
701
+ method: 'POST',
702
+ path: '/api/:v/tool_router/session/:sessionId/search',
703
+ typed: true,
704
+ auth: 'project',
705
+ handle: context => {
706
+ const session = sessionOf(context);
707
+ if (!session) return unknownSession(context);
708
+ const { queries } = SearchBody.parse(context.body);
709
+ return {
710
+ json: searchResponse(
711
+ context,
712
+ session,
713
+ (queries ?? []).map(query => query.use_case)
714
+ ),
715
+ acted: { project: session.projectLabel, userId: session.userId },
716
+ };
717
+ },
718
+ }),
719
+ backend({
720
+ name: 'toolRouter.session.execute',
721
+ method: 'POST',
722
+ path: '/api/:v/tool_router/session/:sessionId/execute',
723
+ typed: true,
724
+ auth: 'project',
725
+ handle: context => {
726
+ const session = sessionOf(context);
727
+ if (!session) return unknownSession(context);
728
+ const request = ExecuteBody.parse(context.body);
729
+ const acted = { project: session.projectLabel, userId: session.userId };
730
+ const outcome = runTool(context.world, {
731
+ projectLabel: session.projectLabel,
732
+ userId: session.userId,
733
+ slug: request.tool_slug,
734
+ args: request.arguments ?? {},
735
+ });
736
+ if (outcome.kind === 'unknown-tool') return { ...unknownTool(request.tool_slug), acted };
737
+ if (outcome.kind === 'not-connected')
738
+ return { ...noActiveConnection(outcome.toolkit), acted };
739
+ return {
740
+ json: { result_type: 'completed', data: outcome.data, error: null, log_id: outcome.logId },
741
+ acted,
742
+ effect: 'tool-executed',
743
+ tool: { slug: request.tool_slug, arguments: request.arguments ?? {} },
744
+ };
745
+ },
746
+ }),
747
+ backend({
748
+ name: 'toolRouter.session.executeMeta',
749
+ method: 'POST',
750
+ path: '/api/:v/tool_router/session/:sessionId/execute_meta',
751
+ typed: true,
752
+ auth: 'project',
753
+ handle: context => {
754
+ const session = sessionOf(context);
755
+ if (!session) return unknownSession(context);
756
+ const request = ExecuteMetaBody.parse(context.body);
757
+ return {
758
+ json: {
759
+ result_type: 'completed',
760
+ data: { slug: request.slug, echoed_arguments: request.arguments ?? {} },
761
+ error: null,
762
+ log_id: context.world.nextLogId(),
763
+ },
764
+ acted: { project: session.projectLabel, userId: session.userId },
765
+ };
766
+ },
767
+ }),
768
+ backend({
769
+ name: 'toolRouter.session.link',
770
+ method: 'POST',
771
+ path: '/api/:v/tool_router/session/:sessionId/link',
772
+ typed: true,
773
+ auth: 'project',
774
+ handle: context => {
775
+ const session = sessionOf(context);
776
+ if (!session) return unknownSession(context);
777
+ const request = SessionLinkBody.parse(context.body);
778
+ const toolkit = context.world.findToolkit(request.toolkit);
779
+ if (!toolkit) return notFound(`Toolkit ${request.toolkit} not found`, 'Toolkit_NotFound');
780
+ const connection = context.world.beginConnection({
781
+ projectLabel: session.projectLabel,
782
+ userId: session.userId,
783
+ toolkit: toolkit.slug,
784
+ alias: request.alias,
785
+ });
786
+ return {
787
+ status: 201,
788
+ json: {
789
+ link_token: `lt_${connection.id}`,
790
+ redirect_url: redirectUrl(context.urls, connection),
791
+ connected_account_id: connection.id,
792
+ },
793
+ acted: { project: session.projectLabel, userId: session.userId },
794
+ effect: 'connection-started',
795
+ };
796
+ },
797
+ }),
798
+ backend({
799
+ name: 'toolRouter.session.toolkits',
800
+ method: 'GET',
801
+ path: '/api/:v/tool_router/session/:sessionId/toolkits',
802
+ typed: true,
803
+ auth: 'project',
804
+ handle: context => {
805
+ const session = sessionOf(context);
806
+ if (!session) return unknownSession(context);
807
+ const { world } = context;
808
+ const wanted = context.query.get('toolkits')?.toLowerCase().split(',');
809
+ const items = world.toolkits
810
+ .filter(toolkit => !wanted || wanted.includes(toolkit.slug))
811
+ .map(toolkit => {
812
+ const connection = world.reportActiveConnection(
813
+ session.projectLabel,
814
+ session.userId,
815
+ toolkit.slug
816
+ );
817
+ return {
818
+ name: toolkit.name,
819
+ slug: toolkit.slug,
820
+ enabled: true,
821
+ is_no_auth: toolkit.noAuth,
822
+ composio_managed_auth_schemes: toolkit.noAuth ? [] : ['OAUTH2'],
823
+ meta: { logo: LOGO, description: toolkit.description },
824
+ connected_account: connection
825
+ ? {
826
+ id: connection.id,
827
+ user_id: connection.userId,
828
+ status: connection.status,
829
+ created_at: SEEDED_AT,
830
+ auth_config: {
831
+ id: connection.authConfigId,
832
+ auth_scheme: 'OAUTH2',
833
+ is_composio_managed: true,
834
+ },
835
+ }
836
+ : null,
837
+ };
838
+ });
839
+ return {
840
+ json: singlePage(items),
841
+ acted: { project: session.projectLabel, userId: session.userId },
842
+ };
843
+ },
844
+ }),
845
+];
846
+
847
+const DEVELOPER_ROUTES: ReadonlyArray<Route> = [
848
+ backend({
849
+ name: 'authConfigs.list',
850
+ method: 'GET',
851
+ path: '/api/:v/auth_configs',
852
+ typed: true,
853
+ auth: 'project',
854
+ handle: ({ world, project, query }) => {
855
+ const toolkit = query.get('toolkit_slug')?.toLowerCase();
856
+ const items = world.authConfigs
857
+ .filter(authConfig => authConfig.projectLabel === project!.label)
858
+ .filter(authConfig => !toolkit || authConfig.toolkit === toolkit)
859
+ .map(authConfig => authConfigItem(authConfig, world));
860
+ return { json: singlePage(items) };
861
+ },
862
+ }),
863
+ backend({
864
+ name: 'authConfigs.retrieve',
865
+ method: 'GET',
866
+ path: '/api/:v/auth_configs/:id',
867
+ typed: true,
868
+ auth: 'project',
869
+ handle: ({ world, project, params }) => {
870
+ const authConfig = world.authConfigs.find(
871
+ candidate => candidate.id === params.id && candidate.projectLabel === project!.label
872
+ );
873
+ return authConfig
874
+ ? { json: authConfigItem(authConfig, world) }
875
+ : notFound(`Auth config ${params.id} not found`, 'AuthConfig_NotFound');
876
+ },
877
+ }),
878
+ backend({
879
+ name: 'connectedAccounts.list',
880
+ method: 'GET',
881
+ path: '/api/:v/connected_accounts',
882
+ typed: true,
883
+ auth: 'project',
884
+ handle: ({ world, project, query, urls }) => {
885
+ const userIds = query.getAll('user_ids').flatMap(value => value.split(','));
886
+ const toolkits = query.getAll('toolkit_slugs').flatMap(value => value.split(','));
887
+ const statuses = query.getAll('statuses').flatMap(value => value.split(','));
888
+ const items = world.connections
889
+ .filter(connection => connection.projectLabel === project!.label)
890
+ .filter(connection => userIds.length === 0 || userIds.includes(connection.userId))
891
+ .filter(connection => toolkits.length === 0 || toolkits.includes(connection.toolkit))
892
+ .filter(connection => statuses.length === 0 || statuses.includes(connection.status))
893
+ .map(connection => connectedAccount(connection, urls));
894
+ return {
895
+ json: singlePage(items),
896
+ acted: { userId: userIds.length === 1 ? (userIds[0] ?? null) : null },
897
+ };
898
+ },
899
+ }),
900
+ backend({
901
+ name: 'connectedAccounts.retrieve',
902
+ method: 'GET',
903
+ path: '/api/:v/connected_accounts/:id',
904
+ typed: true,
905
+ auth: 'project',
906
+ handle: ({ world, project, params, urls }) => {
907
+ const connection = world.connections.find(
908
+ candidate => candidate.id === params.id && candidate.projectLabel === project!.label
909
+ );
910
+ if (connection) world.pollConnection(connection);
911
+ return connection
912
+ ? { json: connectedAccount(connection, urls), acted: { userId: connection.userId } }
913
+ : notFound(`Connected account ${params.id} not found`, 'ConnectedAccount_NotFound');
914
+ },
915
+ }),
916
+ backend({
917
+ name: 'link.create',
918
+ method: 'POST',
919
+ path: '/api/:v/connected_accounts/link',
920
+ typed: true,
921
+ auth: 'project',
922
+ handle: ({ world, project, body, urls }) => {
923
+ const request = LinkCreateBody.parse(body);
924
+ const authConfig = world.authConfigs.find(
925
+ candidate =>
926
+ candidate.id === request.auth_config_id && candidate.projectLabel === project!.label
927
+ );
928
+ if (!authConfig) {
929
+ return notFound(`Auth config ${request.auth_config_id} not found`, 'AuthConfig_NotFound');
930
+ }
931
+ const connection = world.beginConnection({
932
+ projectLabel: project!.label,
933
+ userId: request.user_id,
934
+ toolkit: authConfig.toolkit,
935
+ alias: request.alias,
936
+ });
937
+ return {
938
+ status: 201,
939
+ json: {
940
+ link_token: `lt_${connection.id}`,
941
+ redirect_url: redirectUrl(urls, connection),
942
+ expires_at: SEEDED_EXPIRY,
943
+ connected_account_id: connection.id,
944
+ },
945
+ acted: { userId: request.user_id },
946
+ effect: 'connection-started',
947
+ };
948
+ },
949
+ }),
950
+ backend({
951
+ name: 'tools.execute',
952
+ method: 'POST',
953
+ path: '/api/:v/tools/execute/:slug',
954
+ typed: true,
955
+ auth: 'project',
956
+ handle: ({ world, project, params, body }) => {
957
+ const request = DirectExecuteBody.parse(body);
958
+ const slug = params.slug ?? '';
959
+ const userId =
960
+ request.user_id ??
961
+ world.connections.find(connection => connection.id === request.connected_account_id)
962
+ ?.userId ??
963
+ '';
964
+ const acted = { userId: userId === '' ? null : userId };
965
+ const outcome = runTool(world, {
966
+ projectLabel: project!.label,
967
+ userId,
968
+ slug,
969
+ args: request.arguments ?? {},
970
+ });
971
+ if (outcome.kind === 'unknown-tool') return { ...unknownTool(slug), acted };
972
+ if (outcome.kind === 'not-connected') {
973
+ return {
974
+ status: 400,
975
+ json: errorEnvelope({
976
+ status: 400,
977
+ code: 4302,
978
+ slug: 'ActionExecute_ConnectedAccountNotFound',
979
+ message: `No connected account found for user ${userId} and toolkit ${outcome.toolkit}`,
980
+ }),
981
+ acted,
982
+ };
983
+ }
984
+ return {
985
+ json: { data: outcome.data, error: null, successful: true, log_id: outcome.logId },
986
+ acted,
987
+ effect: 'tool-executed',
988
+ tool: { slug, arguments: request.arguments ?? {} },
989
+ };
990
+ },
991
+ }),
992
+];
993
+
994
+/**
995
+ * The Dashboard procedures behind consumer `composio execute`. The Dashboard
996
+ * resolves the consumer project and the consumer user from the login, runs the
997
+ * tool on the backend, and relays the backend's answer inside a tRPC envelope.
998
+ */
999
+const trpcReply = (outcome: unknown) => ({ result: { data: { json: outcome } } });
1000
+
1001
+const DASHBOARD_ROUTES: ReadonlyArray<Route> = [
1002
+ {
1003
+ name: 'dashboard.execute',
1004
+ role: 'dashboard',
1005
+ method: 'POST',
1006
+ path: '/api/cli/trpc/execute',
1007
+ typed: false,
1008
+ auth: 'none',
1009
+ handle: ({ world, identity, body }) => {
1010
+ const acted = { project: CONSUMER_PROJECT.label, userId: CONSUMER_USER_ID };
1011
+ if (identity.keyClass !== 'user' || !identity.keyKnown) {
1012
+ return {
1013
+ status: 401,
1014
+ json: {
1015
+ error: {
1016
+ json: {
1017
+ message: 'Invalid or expired credentials',
1018
+ code: -32001,
1019
+ data: { code: 'UNAUTHORIZED', httpStatus: 401 },
1020
+ },
1021
+ },
1022
+ },
1023
+ acted,
1024
+ };
1025
+ }
1026
+ const request = ExecuteBody.parse(TrpcBody.parse(body).json);
1027
+ const outcome = runTool(world, {
1028
+ projectLabel: CONSUMER_PROJECT.label,
1029
+ userId: CONSUMER_USER_ID,
1030
+ slug: request.tool_slug,
1031
+ args: request.arguments ?? {},
1032
+ });
1033
+ if (outcome.kind === 'unknown-tool') {
1034
+ const failure = unknownTool(request.tool_slug);
1035
+ return {
1036
+ json: trpcReply({
1037
+ ok: false,
1038
+ status: 404,
1039
+ error: z.object({ error: z.unknown() }).parse(failure.json).error,
1040
+ }),
1041
+ acted,
1042
+ };
1043
+ }
1044
+ if (outcome.kind === 'not-connected') {
1045
+ const failure = noActiveConnection(outcome.toolkit);
1046
+ return {
1047
+ json: trpcReply({ ok: false, status: failure.status, error: failure.json.error }),
1048
+ acted,
1049
+ };
1050
+ }
1051
+ return {
1052
+ json: trpcReply({
1053
+ ok: true,
1054
+ response: {
1055
+ result_type: 'completed',
1056
+ data: outcome.data,
1057
+ error: null,
1058
+ log_id: outcome.logId,
1059
+ },
1060
+ }),
1061
+ acted,
1062
+ effect: 'tool-executed',
1063
+ tool: { slug: request.tool_slug, arguments: request.arguments ?? {} },
1064
+ };
1065
+ },
1066
+ },
1067
+ {
1068
+ name: 'dashboard.executeMeta',
1069
+ role: 'dashboard',
1070
+ method: 'POST',
1071
+ path: '/api/cli/trpc/executeMeta',
1072
+ typed: false,
1073
+ auth: 'none',
1074
+ handle: ({ world, body }) => {
1075
+ const request = ExecuteMetaBody.parse(TrpcBody.parse(body).json);
1076
+ return {
1077
+ json: trpcReply({
1078
+ ok: true,
1079
+ response: {
1080
+ result_type: 'completed',
1081
+ data: { slug: request.slug, echoed_arguments: request.arguments ?? {} },
1082
+ error: null,
1083
+ log_id: world.nextLogId(),
1084
+ },
1085
+ }),
1086
+ acted: { project: CONSUMER_PROJECT.label, userId: CONSUMER_USER_ID },
1087
+ };
1088
+ },
1089
+ },
1090
+];
1091
+
1092
+const AGENT_IDENTITY = {
1093
+ status: 'READY',
1094
+ slug: 'e2e-agent',
1095
+ email: 'e2e-agent@agent.composio.test',
1096
+ composio_agent_key: 'cak_e2e_agent_key_0001',
1097
+ composio: {
1098
+ member_id: 'mem_e2e_agent',
1099
+ org_id: 'ok_e2eagent0001',
1100
+ project_id: 'pr_e2eagent00001',
1101
+ user_api_key: 'uak_e2e_agent_user_key',
1102
+ },
1103
+} as const;
1104
+
1105
+const AGENT_ROUTES: ReadonlyArray<Route> = [
1106
+ {
1107
+ name: 'agents.signup',
1108
+ role: 'agents',
1109
+ method: 'POST',
1110
+ path: '/api/signup',
1111
+ typed: false,
1112
+ auth: 'none',
1113
+ handle: () => ({ json: AGENT_IDENTITY }),
1114
+ },
1115
+ {
1116
+ name: 'agents.whoami',
1117
+ role: 'agents',
1118
+ method: 'GET',
1119
+ path: '/api/whoami',
1120
+ typed: false,
1121
+ auth: 'none',
1122
+ handle: ({ identity }) =>
1123
+ identity.key === AGENT_IDENTITY.composio_agent_key
1124
+ ? { json: AGENT_IDENTITY }
1125
+ : { status: 401, json: { message: 'unauthorized' } },
1126
+ },
1127
+];
1128
+
1129
+const releaseJson = (release: Release, baseUrl: string) => ({
1130
+ tag_name: release.tag,
1131
+ draft: false,
1132
+ prerelease: release.prerelease,
1133
+ assets: release.assets.map(asset => ({
1134
+ name: asset.name,
1135
+ browser_download_url: `${baseUrl}/ComposioHQ/composio/releases/download/${encodeURIComponent(release.tag)}/${asset.name}`,
1136
+ })),
1137
+});
1138
+
1139
+const RELEASE_ROUTES: ReadonlyArray<Route> = [
1140
+ {
1141
+ name: 'github.releases.list',
1142
+ role: 'github-api',
1143
+ method: 'GET',
1144
+ path: '/repos/:owner/:repo/releases',
1145
+ typed: false,
1146
+ auth: 'none',
1147
+ handle: ({ world, urls }) => ({
1148
+ json: world.releases.map(release => releaseJson(release, urls.backend)),
1149
+ }),
1150
+ },
1151
+ {
1152
+ name: 'github.releases.byTag',
1153
+ role: 'github-api',
1154
+ method: 'GET',
1155
+ path: '/repos/:owner/:repo/releases/tags/:tag',
1156
+ typed: false,
1157
+ auth: 'none',
1158
+ handle: ({ world, params, urls }) => {
1159
+ const release = world.releases.find(candidate => candidate.tag === params.tag);
1160
+ return release
1161
+ ? { json: releaseJson(release, urls.backend) }
1162
+ : { status: 404, json: { message: 'Not Found', status: '404' } };
1163
+ },
1164
+ },
1165
+ {
1166
+ name: 'github.releases.download',
1167
+ role: 'github-download',
1168
+ method: 'GET',
1169
+ path: '/:owner/:repo/releases/download/:tag/:asset',
1170
+ typed: false,
1171
+ auth: 'none',
1172
+ handle: ({ world, params }) => {
1173
+ const asset = world.releases
1174
+ .find(candidate => candidate.tag === params.tag)
1175
+ ?.assets.find(candidate => candidate.name === params.asset);
1176
+ return asset ? { bytes: asset.read() } : { status: 404, text: 'Not Found\n' };
1177
+ },
1178
+ },
1179
+];
1180
+
1181
+const TELEMETRY_ROUTES: ReadonlyArray<Route> = [
1182
+ {
1183
+ name: 'posthog.capture',
1184
+ role: 'posthog',
1185
+ method: 'POST',
1186
+ path: '/posthog/i/v0/e/',
1187
+ typed: false,
1188
+ auth: 'none',
1189
+ handle: () => ({ json: { status: 1 } }),
1190
+ },
1191
+];
1192
+
1193
+export const ROUTES: ReadonlyArray<Route> = [
1194
+ ...ACCOUNT_ROUTES,
1195
+ ...LOGIN_ROUTES,
1196
+ ...CATALOG_ROUTES,
1197
+ ...SESSION_ROUTES,
1198
+ ...DEVELOPER_ROUTES,
1199
+ ...DASHBOARD_ROUTES,
1200
+ ...AGENT_ROUTES,
1201
+ ...RELEASE_ROUTES,
1202
+ ...TELEMETRY_ROUTES,
1203
+];
1204
+
1205
+export { AGENT_IDENTITY };