@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, 04:45 UTC

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