@devries-cameron20 / composio-1 / commits / 90680d796
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.

docs(core): trim verbose JSDoc and consolidate mastra-ref test setup

Pure shrink — no behavior change, no coverage loss. - `dereferenceJsonSchema` JSDoc cut from ~45 lines to ~10. The trimmed prose duplicated the changeset entry and the maintainer comments inline next to the relevant code; a user hovering the export gets a tighter contract instead of an essay. - Two multi-line maintainer comments in the closure shortened to one line each. The "function declaration so cloneChildren can reference walk via hoisting" comment is now a single sentence. - `mastra-ref.test.ts` extracts `provider`/`exec`/`wrapTool` boilerplate into a `beforeEach`. Three near-identical setups collapse to one. The redundant "does not throw" test folds into the shared setup — any throw now fails all three real assertions instead. - `findProperty` test helper simplified. Diff impact: -113 / +36 in this commit; total PR shrink ~95 LOC.

jkomyno committed Apr 30, 2026 at 02:03 UTC 90680d79658603b314ccfa856ffb22a0706862d4
2 files changed +36 -113
ts/packages/core/src/utils/jsonSchema.ts
+11 -47
@@ -51,49 +51,15 @@ const resolvePointer = (root: Record<string, unknown>, pointer: string): unknown
51 };
52
53 /**
54 - * Inlines internal JSON Schema `$ref` pointers (`#/$defs/...` and the
55 - * legacy `#/definitions/...`) so the returned schema can be safely handed
56 - * to consumers — like AJV in `@mastra/schema-compat` — that don't tolerate
57 - * unresolved references.
54 + * Inlines internal JSON Schema `$ref` pointers (`#/$defs/...` and legacy
55 + * `#/definitions/...`) so the returned schema can be safely handed to
56 + * consumers that don't tolerate unresolved references (e.g. AJV in
57 + * `@mastra/schema-compat`). External (`http://`, `https://`, …) refs are
58 + * left untouched. Cycles are broken with `{ type: 'object',
59 + * additionalProperties: true }`. The input is never mutated.
60 *
59 - * The traversal is reflective (no allow-list of JSON Schema keywords), so
60 - * future applicators (`unevaluatedProperties`, `dependentSchemas`, …) are
61 - * covered automatically. Sibling keywords next to `$ref` are shallow-merged
62 - * per Draft 2020-12 semantics — the sibling wins on collision so a caller's
63 - * `description` or `default` overrides the target's. Recursive `$ref`
64 - * chains are broken with `{ type: 'object', additionalProperties: true }`,
65 - * matching the upstream Mastra recommendation in
66 - * {@link https://github.com/mastra-ai/mastra/issues/15341 mastra-ai/mastra#15341}.
67 - *
68 - * The input schema is not mutated: every node is deep-cloned. `$defs` and
69 - * `definitions` are stripped from the returned root once everything
70 - * reachable is inlined — AJV strict-mode otherwise complains about unused
71 - * definitions.
72 - *
73 - * External `$ref` pointers (`http://`, `https://`, `file://`, …) are left
74 - * untouched: the caller may forward them to a consumer that resolves them
75 - * natively.
76 - *
77 - * @param schema - The JSON Schema to dereference. May be any plain object.
78 - * @returns A new schema with internal `$ref` pointers inlined.
79 - *
80 - * @throws {JsonSchemaRefResolutionError} When an internal pointer is
81 - * malformed, points at a missing target, or chains past the depth cap.
82 - *
83 - * @example
84 - * ```ts
85 - * dereferenceJsonSchema({
86 - * type: 'object',
87 - * properties: { user: { $ref: '#/$defs/User' } },
88 - * $defs: { User: { type: 'object', properties: { id: { type: 'string' } } } },
89 - * });
90 - * // {
91 - * // type: 'object',
92 - * // properties: {
93 - * // user: { type: 'object', properties: { id: { type: 'string' } } },
94 - * // },
95 - * // }
96 - * ```
61 + * @throws {JsonSchemaRefResolutionError} on malformed pointers, missing
62 + * targets, or chains past the depth cap.
63 */
64 export function dereferenceJsonSchema<T = unknown>(schema: T): T {
65 if (!isPlainObject(schema)) return schema;
@@ -101,9 +67,8 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
67 const root = schema as Record<string, unknown>;
68 const visiting = new WeakSet<object>();
69
104 - // Filter `__proto__`/`constructor`/`prototype` keys to avoid altering the
105 - // prototype of the cloned output node (which can break downstream
106 - // `Object.keys` / `in` checks even though the global prototype is safe).
70 + // POLLUTING_KEYS filter prevents an attacker-shaped $defs entry from altering
71 + // the cloned node's prototype.
72 const cloneChildren = (
73 obj: Record<string, unknown>,
74 visitedRefs: ReadonlySet<string>,
@@ -116,8 +81,7 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
81 .map(([k, v]) => [k, walk(v, visitedRefs, chainDepth, nodeDepth + 1)])
82 );
83
119 - // Function declaration so `cloneChildren` can reference `walk` despite being
120 - // declared earlier (function declarations are hoisted within the closure).
84 + // `function` (not `const`) so `cloneChildren` above can call it via hoisting.
85 function walk(
86 node: unknown,
87 visitedRefs: ReadonlySet<string>,
ts/packages/providers/mastra/test/mastra-ref.test.ts
+25 -66
@@ -1,20 +1,15 @@
1 /**
2 - * Integration test for the Mastra provider against the **real**
3 - * `@mastra/schema-compat` package (no `vi.mock` for it). This is the regression
4 - * test for [PLEN-2244]: a Composio tool whose `inputParameters` carry a `$ref`
5 - * (legal under both Draft 7 and 2020-12).
2 + * Regression test for the Mastra provider against the **real**
3 + * `@mastra/schema-compat` (no `vi.mock` for it). Without dereferencing,
4 + * `applyCompatLayer` silently degrades a `$ref`-typed property to a permissive
5 + * `anyOf` of all primitives — losing the type info from `$defs`. We assert
6 + * the post-wrap schemas preserve the structure described by `$defs`.
7 *
7 - * Without dereferencing, `applyCompatLayer` silently *degrades* the `$ref`-typed
8 - * property to a permissive `anyOf` of all primitives — losing the type
9 - * information from `$defs`. This test asserts the post-wrap `inputSchema`
10 - * preserves the structure described by `$defs`, which is only possible if
11 - * `$ref` is resolved before the conversion.
12 - *
13 - * Vitest mock scoping is per-file by default, so the top-level `vi.mock` for
14 - * `@mastra/schema-compat` in `mastra.test.ts` does **not** leak into this file.
8 + * Vitest mock scoping is per-file by default, so the top-level `vi.mock`
9 + * for `@mastra/schema-compat` in `mastra.test.ts` does not leak here.
10 */
11
17 -import { describe, it, expect, vi } from 'vitest';
12 +import { describe, it, expect, vi, beforeEach } from 'vitest';
13 import type { Tool } from '@composio/core';
14 import { MastraProvider } from '../src';
15
@@ -27,22 +22,17 @@ const containsRef = (value: unknown): boolean => {
22
23 const findProperty = (schema: unknown, key: string): Record<string, unknown> | undefined => {
24 if (schema === null || typeof schema !== 'object') return undefined;
30 - const node = schema as Record<string, unknown>;
31 - if (node.properties && typeof node.properties === 'object') {
32 - const props = node.properties as Record<string, unknown>;
33 - if (key in props) return props[key] as Record<string, unknown>;
34 - for (const value of Object.values(props)) {
35 - const found = findProperty(value, key);
36 - if (found) return found;
37 - }
38 - }
39 - for (const value of Object.values(node)) {
25 + for (const value of Object.values(schema as Record<string, unknown>)) {
26 if (Array.isArray(value)) {
27 for (const item of value) {
28 const found = findProperty(item, key);
29 if (found) return found;
30 }
31 } else if (typeof value === 'object' && value !== null) {
32 + const props = value as Record<string, unknown> as Record<string, unknown>;
33 + if (key in props && typeof props[key] === 'object') {
34 + return props[key] as Record<string, unknown>;
35 + }
36 const found = findProperty(value, key);
37 if (found) return found;
38 }
@@ -63,72 +53,41 @@ const refTool: Tool = {
53 properties: { user: { $ref: '#/$defs/User' } as never },
54 required: ['user'],
55 $defs: {
66 - User: {
67 - type: 'object',
68 - properties: { id: { type: 'string' } },
69 - required: ['id'],
70 - },
56 + User: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
57 },
58 } as unknown as Tool['inputParameters'],
59 outputParameters: {
60 type: 'object',
61 properties: { item: { $ref: '#/definitions/Item' } as never },
62 definitions: {
77 - Item: {
78 - type: 'object',
79 - properties: { sku: { type: 'string' } },
80 - required: ['sku'],
81 - },
63 + Item: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'] },
64 },
65 } as unknown as Tool['outputParameters'],
66 };
67
86 -describe('MastraProvider regression: PLEN-2244 ($ref in JSON Schema)', () => {
87 - it('does not throw when wrapping a tool whose schema uses $ref / $defs', () => {
88 - const provider = new MastraProvider();
89 - const executeToolFn = vi.fn().mockResolvedValue({ data: {}, error: null, successful: true });
90 - provider._setExecuteToolFn(executeToolFn);
91 -
92 - expect(() => provider.wrapTool(refTool, executeToolFn)).not.toThrow();
93 - });
68 +describe('MastraProvider regression: $ref in JSON Schema', () => {
69 + let wrapped: { inputSchema: unknown; outputSchema: unknown };
70
95 - it('preserves type information from $defs (does not degrade $ref to permissive anyOf)', () => {
71 + beforeEach(() => {
72 const provider = new MastraProvider();
97 - const executeToolFn = vi.fn().mockResolvedValue({ data: {}, error: null, successful: true });
98 - provider._setExecuteToolFn(executeToolFn);
99 -
100 - const wrapped = provider.wrapTool(refTool, executeToolFn) as { inputSchema: unknown };
73 + const exec = vi.fn().mockResolvedValue({ data: {}, error: null, successful: true });
74 + provider._setExecuteToolFn(exec);
75 + wrapped = provider.wrapTool(refTool, exec) as typeof wrapped;
76 + });
77
102 - // Without the dereference step, `$ref` is silently dropped during
103 - // JSON-Schema → Zod → JSON-Schema round-trip and the `id` field disappears
104 - // entirely (the property gets degraded to a permissive `anyOf`).
78 + it('preserves type info from $defs (no degraded permissive anyOf)', () => {
79 const idProp = findProperty(wrapped.inputSchema, 'id');
80 expect(idProp).toBeDefined();
81 expect(idProp?.type).toBe('string');
82 });
83
110 - it('preserves type information from `definitions` on outputParameters (Draft 7)', () => {
111 - const provider = new MastraProvider();
112 - const executeToolFn = vi.fn().mockResolvedValue({ data: {}, error: null, successful: true });
113 - provider._setExecuteToolFn(executeToolFn);
114 -
115 - const wrapped = provider.wrapTool(refTool, executeToolFn) as { outputSchema: unknown };
116 -
84 + it('preserves type info from Draft-7 `definitions` on the output schema', () => {
85 const skuProp = findProperty(wrapped.outputSchema, 'sku');
86 expect(skuProp).toBeDefined();
87 expect(skuProp?.type).toBe('string');
88 });
89
122 - it('does not leave any $ref in the produced schemas', () => {
123 - const provider = new MastraProvider();
124 - const executeToolFn = vi.fn().mockResolvedValue({ data: {}, error: null, successful: true });
125 - provider._setExecuteToolFn(executeToolFn);
126 -
127 - const wrapped = provider.wrapTool(refTool, executeToolFn) as {
128 - inputSchema: unknown;
129 - outputSchema: unknown;
130 - };
131 -
90 + it('leaves no $ref in the produced schemas', () => {
91 expect(containsRef(wrapped.inputSchema)).toBe(false);
92 expect(containsRef(wrapped.outputSchema)).toBe(false);
93 });