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 127 lines 5.14 KB
Raw
1 /**
2 * Output-schema leniency for the Mastra provider.
3 *
4 * Mastra validates every tool result against the tool's `outputSchema` via
5 * `validateToolOutput`; on a mismatch it drops the data and substitutes an
6 * error. Composio's API-supplied output schemas, however, are strict: optional
7 * fields are typed as non-nullable primitives (`{ type: 'string' }`) and
8 * objects carry `additionalProperties: false`. Real third-party APIs (Linear,
9 * Notion, Jira, Slack, …) routinely return `null` for unset optional fields and
10 * occasionally extra keys, so strict validation rejects perfectly good
11 * responses and truncates the tool output the model sees.
12 *
13 * Output validation of opaque third-party pass-through payloads provides little
14 * value and causes real breakage, so we relax the output schema before handing
15 * it to `@mastra/schema-compat`:
16 *
17 * - every typed node is made nullable (`type: 'string'` → `['string', 'null']`)
18 * - objects with `additionalProperties: false` (or unset) allow extra keys
19 * - `enum`/`const` are widened to also admit `null` — they constrain the
20 * *value* independently of `type`, so making the type nullable is not enough
21 * - `required` is dropped, since real APIs omit unset fields entirely rather
22 * than returning `null` for them, so requiring any field rejects good output
23 *
24 * All four changes only *widen* what validates, so any payload that passed
25 * before still passes — there is no behavioural change for already-valid output.
26 *
27 * See https://github.com/ComposioHQ/composio/issues/3047.
28 */
29
30 // JSON-Schema keywords whose values are themselves schemas and sit in a
31 // *positive* position, so relaxing them widens the parent (recurse into them).
32 //
33 // `not` is deliberately excluded: it negates its subschema, so relaxing the
34 // inner schema (e.g. making it nullable) would *narrow* what the parent admits —
35 // a `null` valid under `not: { type: 'string' }` would start failing. That is
36 // the opposite of this helper's only-widen guarantee, so `not` is left as-is.
37 const SUBSCHEMA_KEYS = ['items', 'additionalItems', 'contains'] as const;
38 // Keywords whose values are arrays of schemas.
39 const SUBSCHEMA_LIST_KEYS = ['anyOf', 'oneOf', 'allOf', 'prefixItems'] as const;
40 // Keywords whose values are maps of name -> schema.
41 const SUBSCHEMA_MAP_KEYS = ['properties', 'patternProperties', '$defs', 'definitions'] as const;
42
43 function isPlainObject(value: unknown): value is Record<string, unknown> {
44 return typeof value === 'object' && value !== null && !Array.isArray(value);
45 }
46
47 function addNullToType(type: unknown): unknown {
48 if (typeof type === 'string') {
49 return type === 'null' ? type : [type, 'null'];
50 }
51 if (Array.isArray(type)) {
52 return type.includes('null') ? type : [...type, 'null'];
53 }
54 return type;
55 }
56
57 /**
58 * Recursively returns a leniency-relaxed copy of a JSON schema for use as a
59 * Mastra `outputSchema`. The input is never mutated.
60 */
61 export function relaxOutputSchema<T>(schema: T): T {
62 if (!isPlainObject(schema)) return schema;
63
64 const result: Record<string, unknown> = { ...schema };
65
66 // Decide object-ness from the *original* type before it is rewritten below.
67 const originalType = result.type;
68 const isObjectSchema =
69 originalType === 'object' ||
70 (Array.isArray(originalType) && originalType.includes('object')) ||
71 'properties' in result ||
72 'patternProperties' in result;
73
74 // Make any typed node nullable so a `null` from the upstream API validates.
75 if ('type' in result) {
76 result.type = addNullToType(result.type);
77 }
78
79 // `enum`/`const` restrict the value regardless of `type`, so a nullable type
80 // alone would still reject a `null`. Widen them to admit `null` too; `const`
81 // (a single allowed value) becomes a two-member nullable `enum`.
82 if ('const' in result) {
83 result.enum = [result.const, null];
84 delete result.const;
85 } else if (Array.isArray(result.enum) && !result.enum.includes(null)) {
86 result.enum = [...result.enum, null];
87 }
88
89 // Drop `required`: third-party APIs omit unset fields entirely (not just
90 // return `null`), so requiring any field would reject otherwise-valid output.
91 if ('required' in result) {
92 delete result.required;
93 }
94
95 // Allow extra keys on objects that forbid (or omit) additional properties.
96 // A sub-schema value is preserved and recursed into instead of overwritten.
97 if (isPlainObject(result.additionalProperties)) {
98 result.additionalProperties = relaxOutputSchema(result.additionalProperties);
99 } else if (
100 isObjectSchema &&
101 (result.additionalProperties === false || result.additionalProperties === undefined)
102 ) {
103 result.additionalProperties = true;
104 }
105
106 for (const key of SUBSCHEMA_KEYS) {
107 if (key in result) result[key] = relaxOutputSchema(result[key]);
108 }
109
110 for (const key of SUBSCHEMA_LIST_KEYS) {
111 const value = result[key];
112 if (Array.isArray(value)) {
113 result[key] = value.map(entry => relaxOutputSchema(entry));
114 }
115 }
116
117 for (const key of SUBSCHEMA_MAP_KEYS) {
118 const value = result[key];
119 if (isPlainObject(value)) {
120 result[key] = Object.fromEntries(
121 Object.entries(value).map(([name, sub]) => [name, relaxOutputSchema(sub)])
122 );
123 }
124 }
125
126 return result as T;
127 }