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 171 lines 6 KB
Raw
1 import {
2 BaseAgenticProvider,
3 type ExecuteToolFn,
4 type McpServerGetResponse,
5 type McpUrlResponse,
6 normalizeToolArguments,
7 removeNonRequiredProperties,
8 type Tool,
9 type ToolExecuteResponse,
10 } from '@composio/core';
11 import type { JsonValue } from 'eve/connections';
12 import { type ToolContext, type ToolDefinition, defineTool } from 'eve/tools';
13 import type { ApprovalContext } from 'eve/tools/approval';
14 import { withDurableClosure } from './durable';
15 import { applyHooks, type EveProviderHooks } from './hooks';
16
17 export type EveTool = ToolDefinition<Record<string, unknown>, ToolExecuteResponse>;
18 export type EveToolCollection = Record<string, EveTool>;
19 export type EveNeedsApproval = (
20 tool: Tool,
21 context: ApprovalContext<Record<string, unknown>>
22 ) => boolean;
23
24 const MULTI_EXECUTE_TOOL_SLUG = 'COMPOSIO_MULTI_EXECUTE_TOOL';
25
26 const toEveInputSchema = (tool: Tool, strict?: boolean): Record<string, JsonValue> => {
27 const params = tool.inputParameters;
28 if (!params) return { type: 'object', properties: {} };
29 if (!strict || params.type !== 'object') return params as Record<string, JsonValue>;
30
31 return removeNonRequiredProperties({
32 ...params,
33 properties: { ...params.properties },
34 }) as Record<string, JsonValue>;
35 };
36
37 const isProtectedToolItem = (item: unknown, protectedSlugs: ReadonlySet<string>): boolean => {
38 if (typeof item !== 'object' || item === null) return false;
39
40 const toolSlug = (item as Record<string, unknown>).tool_slug;
41 if (typeof toolSlug !== 'string') return false;
42
43 return protectedSlugs.has(toolSlug.toUpperCase());
44 };
45
46 /** Require approval for direct calls and matching entries inside a multi-execute call. */
47 export const requireApprovalForTools = (...toolSlugs: string[]): EveNeedsApproval => {
48 const protectedSlugs = new Set(toolSlugs.map(slug => slug.toUpperCase()));
49 return (tool, context) => {
50 const normalizedToolSlug = tool.slug.toUpperCase();
51 if (protectedSlugs.has(normalizedToolSlug)) return true;
52 if (normalizedToolSlug !== MULTI_EXECUTE_TOOL_SLUG) return false;
53
54 const requestedTools = context.toolInput?.tools;
55 if (!Array.isArray(requestedTools)) return false;
56
57 return requestedTools.some(item => isProtectedToolItem(item, protectedSlugs));
58 };
59 };
60
61 export interface EveProviderOptions {
62 strict?: boolean;
63 hooks?: EveProviderHooks;
64 needsApproval?: EveNeedsApproval;
65 }
66
67 /** Live state one `wrapTools` call produced, which its durable callbacks re-attach to. */
68 interface ToolBinding {
69 readonly tools: ReadonlyMap<string, Tool>;
70 readonly executeTool: ExecuteToolFn;
71 readonly options: EveProviderOptions;
72 }
73
74 /** The JSON snapshot eve persists for each wrapped tool's callbacks. */
75 type ComposioToolClosure = { slug: string; binding: string };
76
77 /**
78 * Bindings for every resolve in this process, keyed by the id stamped into the
79 * closure. `executeTool` is bound to one Composio session, so a closure must
80 * name the resolve that produced it rather than just the slug: sessions for
81 * different users share one provider and would otherwise cross-execute. The
82 * map is module-level because eve's callback registry is keyed by tool name
83 * only, so a second `EveProvider` in the process replays through the same
84 * callbacks. Entries live as long as the process; eve can resume a parked
85 * call at any time. Ids carry a per-process token so a closure persisted by
86 * an earlier process fails the lookup instead of matching whichever resolve
87 * reused its counter value.
88 */
89 const bindings = new Map<string, ToolBinding>();
90 const processToken = globalThis.crypto.randomUUID();
91 let nextBindingId = 0;
92
93 const bind = (binding: ToolBinding): string => {
94 const id = `${processToken}:${++nextBindingId}`;
95 bindings.set(id, binding);
96 return id;
97 };
98
99 const requireBinding = ({ slug, binding }: ComposioToolClosure): ToolBinding & { tool: Tool } => {
100 const bound = bindings.get(binding);
101 const tool = bound?.tools.get(slug);
102 if (!bound || !tool) {
103 throw new Error(
104 `Composio tool "${slug}" has no executor in this process. Resolve the session's tools again before calling it.`
105 );
106 }
107 return { ...bound, tool };
108 };
109
110 const execute = async (
111 closure: ComposioToolClosure,
112 input: Record<string, unknown>,
113 context: ToolContext
114 ): Promise<ToolExecuteResponse> => {
115 const { executeTool, options } = requireBinding(closure);
116 return applyHooks(
117 options.hooks ?? {},
118 closure.slug,
119 normalizeToolArguments(input, closure.slug),
120 executeTool,
121 context
122 );
123 };
124
125 // Only stamped on tools whose binding carries a policy, so the policy is set here.
126 const approve = (
127 closure: ComposioToolClosure,
128 context: ApprovalContext<Record<string, unknown>>
129 ): boolean => {
130 const { tool, options } = requireBinding(closure);
131 return options.needsApproval!(tool, context);
132 };
133
134 export class EveProvider extends BaseAgenticProvider<
135 EveToolCollection,
136 EveTool,
137 McpServerGetResponse
138 > {
139 readonly name = 'eve';
140
141 constructor(private readonly options: EveProviderOptions = {}) {
142 super();
143 }
144
145 wrapTool(tool: Tool, executeTool: ExecuteToolFn): EveTool {
146 return this.wrapTools([tool], executeTool)[tool.slug];
147 }
148
149 wrapTools(tools: Tool[], executeTool: ExecuteToolFn): EveToolCollection {
150 const binding = bind({
151 tools: new Map(tools.map(tool => [tool.slug, tool])),
152 executeTool,
153 options: this.options,
154 });
155 return Object.fromEntries(tools.map(tool => [tool.slug, this.defineBoundTool(tool, binding)]));
156 }
157
158 wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
159 return data.map(item => ({ url: new URL(item.url), name: item.name })) as McpServerGetResponse;
160 }
161
162 private defineBoundTool(tool: Tool, binding: string): EveTool {
163 const closure: ComposioToolClosure = { slug: tool.slug, binding };
164 return defineTool<Record<string, unknown>, ToolExecuteResponse>({
165 description: tool.description ?? tool.name,
166 inputSchema: toEveInputSchema(tool, this.options.strict),
167 approval: this.options.needsApproval ? withDurableClosure(closure, approve) : undefined,
168 execute: withDurableClosure(closure, execute),
169 });
170 }
171 }