@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 215 lines 7.94 KB
Raw
1 /**
2 * Mastra Provider
3 *
4 * This provider provides a set of tools for interacting with Mastra.ai
5 *
6 * @packageDocumentation
7 * @module providers/mastra
8 */
9 import {
10 BaseAgenticProvider,
11 Tool,
12 ExecuteToolFn,
13 McpUrlResponse,
14 dereferenceJsonSchema,
15 logger,
16 omitNullToolArguments,
17 toStrictJsonSchema,
18 telemetry,
19 type UnresolvedRefReason,
20 normalizeToolArguments,
21 } from '@composio/core';
22 import { applyCompatLayer } from '@mastra/schema-compat';
23 import { createTool } from '@mastra/core/tools';
24 import { relaxOutputSchema } from './relax-output-schema';
25
26 export type MastraTool = ReturnType<typeof createTool>;
27
28 export interface MastraToolCollection {
29 [key: string]: MastraTool;
30 }
31
32 export interface MastraUrlMap {
33 [name: string]: { url: string };
34 }
35
36 export class MastraProvider extends BaseAgenticProvider<
37 MastraToolCollection,
38 MastraTool,
39 MastraUrlMap
40 > {
41 readonly name = 'mastra';
42 private strict: boolean | null;
43 // Tracks the (toolSlug, ref) pairs we've already warned about, so wrapping
44 // the same tool many times during a single SDK session does not flood the
45 // logs. Reset is only via constructing a new provider.
46 private warnedDanglingRefs = new Set<string>();
47
48 /**
49 * Creates a new instance of the MastraProvider.
50 *
51 * This provider enables integration with the Mastra AI SDK,
52 * allowing Composio tools to be used with Mastra AI applications.
53 *
54 * @param param0
55 * @param param0.strict - Whether to use strict mode for tool execution
56 * @returns A new instance of the MastraProvider
57 *
58 * @example
59 * ```typescript
60 * import { Composio } from '@composio/core';
61 * import { MastraProvider } from '@composio/mastra';
62 *
63 * const composio = new Composio({
64 * apiKey: 'your-composio-api-key',
65 * provider: new MastraProvider(),
66 * });
67 * ```
68 */
69 constructor({ strict = false }: { strict?: boolean } = {}) {
70 super();
71 this.strict = strict;
72 }
73
74 /**
75 * Transform an MCP URL response into the Mastra provider's format.
76 * Mastra expects a URL map keyed by server name, so each entry is
77 * reduced into an object of `{ [name]: { url } }`.
78 *
79 * @param data - The MCP URL response data
80 * @returns The MCP servers as a Mastra URL map
81 */
82 wrapMcpServerResponse(data: McpUrlResponse): MastraUrlMap {
83 // Transform to Mastra's URL map format
84 return data.reduce((acc: MastraUrlMap, item) => {
85 acc[item.name] = { url: item.url };
86 return acc;
87 }, {});
88 }
89
90 wrapTool(tool: Tool, executeTool: ExecuteToolFn): MastraTool {
91 const inputParams = tool.inputParameters;
92
93 // Strict mode applies OpenAI's structured-output contract at every
94 // depth: all properties required, closed objects, optional properties
95 // widened to accept null instead of being dropped. Tools whose schema
96 // strict mode cannot express keep their original schema.
97 let parameters: Record<string, unknown> | undefined = inputParams as
98 Record<string, unknown> | undefined;
99 let strictSource: Record<string, unknown> | undefined;
100 if (this.strict && inputParams) {
101 const strict = toStrictJsonSchema(inputParams);
102 if (strict.unsupported.length > 0) {
103 const reasons = strict.unsupported
104 .map(entry => `${entry.path || '<root>'}: ${entry.keyword} (${entry.detail})`)
105 .join('; ');
106 logger.warn(
107 `[composio/mastra] Tool ${JSON.stringify(tool.slug)} keeps its non-strict schema because it cannot be expressed as strict structured outputs: ${reasons}`
108 );
109 } else {
110 parameters = strict.schema;
111 strictSource = strict.source;
112 }
113 }
114
115 // Inline internal $ref pointers before handing the schema to
116 // @mastra/schema-compat. AJV (bundled inside schema-compat) refuses to
117 // compile a schema with unresolved $ref, and the upstream JSON-Schema →
118 // Zod converter silently degrades $ref-typed properties to a permissive
119 // anyOf — losing the type info from $defs. See
120 // https://github.com/mastra-ai/mastra/issues/15341.
121 //
122 // Some Composio-API-supplied tools emit a `$ref` into `#/$defs/...`
123 // without ever declaring `$defs` (e.g. `GMAIL_FETCH_EMAILS`). Strict
124 // dereferencing throws on this, which crashes `tools.get` upfront. Opt
125 // into `'sentinel'` so the dangling branch becomes a permissive object
126 // schema instead, and emit a single warn per (toolSlug, ref) pair so the
127 // degraded shape is observable. See
128 // https://github.com/ComposioHQ/composio/issues/3307.
129 const onReplace = (ref: string, reason: UnresolvedRefReason) =>
130 this.warnDanglingRefOnce(tool, ref, reason);
131
132 const inputSchema = applyCompatLayer({
133 schema: dereferenceJsonSchema(parameters ?? {}, {
134 onUnresolved: 'sentinel',
135 onReplace,
136 }),
137 compatLayers: [],
138 mode: 'jsonSchema',
139 });
140
141 // Relax the output schema before compiling it: Composio's API-supplied
142 // output schemas are strict (non-nullable primitives, additionalProperties
143 // false), but third-party APIs return `null` for unset optional fields and
144 // sometimes extra keys. Mastra validates results against this schema and
145 // drops mismatching data, so without this every such response is truncated.
146 // See https://github.com/ComposioHQ/composio/issues/3047.
147 const outputSchema = applyCompatLayer({
148 schema: relaxOutputSchema(
149 dereferenceJsonSchema(tool.outputParameters ?? {}, {
150 onUnresolved: 'sentinel',
151 onReplace,
152 })
153 ),
154 compatLayers: [],
155 mode: 'jsonSchema',
156 });
157
158 const mastraTool = createTool({
159 id: tool.slug,
160 description: tool.description ?? '',
161 inputSchema,
162 outputSchema,
163 execute: async (inputData, _context) => {
164 // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
165 const normalized = normalizeToolArguments(inputData, tool.slug);
166 // Under strict mode optional parameters are emitted as required-nullable,
167 // so a null the tool's own schema does not accept means "omitted".
168 const result = await executeTool(
169 tool.slug,
170 strictSource ? omitNullToolArguments(normalized, strictSource) : normalized
171 );
172 return result;
173 },
174 });
175
176 return mastraTool;
177 }
178
179 wrapTools(tools: Tool[], executeTool: ExecuteToolFn): MastraToolCollection {
180 return tools.reduce((acc, tool) => {
181 acc[tool.slug] = this.wrapTool(tool, executeTool);
182 return acc;
183 }, {} as MastraToolCollection);
184 }
185
186 private warnDanglingRefOnce(tool: Tool, ref: string, reason: UnresolvedRefReason): void {
187 const key = `${tool.slug}::${ref}`;
188 if (this.warnedDanglingRefs.has(key)) return;
189 this.warnedDanglingRefs.add(key);
190 const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
191 // `tool.slug`, `toolkitSlug`, and `ref` originate from the upstream API
192 // schema. Quoting via `JSON.stringify` neutralizes embedded newlines /
193 // ANSI escape sequences / control bytes that would otherwise forge log
194 // lines or corrupt terminals (CWE-117).
195 logger.warn(
196 `[composio/mastra] Tool ${JSON.stringify(tool.slug)} ` +
197 `(toolkit ${JSON.stringify(toolkitSlug)}) declares ` +
198 `$ref ${JSON.stringify(ref)} but no matching $defs/definitions entry ` +
199 `(${reason}). Falling back to a permissive object schema for this ` +
200 `branch — the wrapped Mastra tool will validate this property loosely. ` +
201 `Tracked in https://github.com/ComposioHQ/composio/issues/3307.`
202 );
203 // Fire-and-forget aggregate signal so the Composio team can prioritize the
204 // upstream API fix from real data. `telemetry.sendMetric` short-circuits
205 // when `COMPOSIO_DISABLE_TELEMETRY=true` and swallows network errors.
206 void telemetry.sendMetric([
207 {
208 functionName: 'composio.mastra.wrapTool.danglingRef',
209 timestamp: Date.now() / 1000,
210 props: { toolSlug: tool.slug, toolkitSlug, ref, reason },
211 metadata: { provider: 'mastra' },
212 },
213 ]);
214 }
215 }