@devries-cameron20 / composio Mirror · read-only / commits / aaabf5e2a
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, 19:45 UTC

fix(mastra): relax output schema so API nulls and extra keys pass validation (#3585)

## Problem Closes #3047. `MastraProvider.wrapTool` passes each tool's `outputParameters` to Mastra's `createTool` as `outputSchema`, and Mastra validates every tool result against it via `validateToolOutput` — on a mismatch it **drops the data and substitutes an error**. Composio's API-supplied output schemas are strict: optional fields are typed as non-nullable primitives (`{ type: "string" }`) and objects carry `additionalProperties: false`. Real third-party APIs (Linear, Notion, Jira, Slack, …) routinely return `null` for unset optional fields (`avatarUrl`, `assignee`, `description`, …) and occasionally extra keys. So strict validation rejects perfectly good responses and **truncates the tool output the model sees** — affecting a wide range of connector tools. This is the recommended fix (#2) from the issue: output validation of opaque third-party pass-through payloads provides little value and causes real breakage. ## What this changes A new `relaxOutputSchema` helper walks the (already dereferenced) output JSON schema and, non-mutating: - makes every typed node nullable — `type: "string"` → `["string", "null"]` (handles string and array forms, idempotent) - sets `additionalProperties: true` on object nodes that forbid (or omit) extra keys; a schema-valued `additionalProperties` is preserved and recursed into - recurses through `properties`, `patternProperties`, `items`, `anyOf`/`oneOf`/`allOf`, `$defs`/`definitions`, etc. `wrapTool` applies it to the output schema only (input schemas are untouched) before handing it to `@mastra/schema-compat`. ## Why this approach Both transforms only **widen** what validates, so any payload that passed before still passes — there is no behavioural change for already-valid output, and no breaking change. It keeps the existing `dereferenceJsonSchema` → `applyCompatLayer` pipeline intact and adds one focused, unit-tested step. The `$ref`/`$defs` type-preservation behaviour from the existing regression suite is retained (the dereferenced inner type is kept, just made nullable). ## Testing - New `test/relax-output-schema.test.ts` — 11 unit cases (nullable primitives, idempotency, nested objects, `additionalProperties` flip/preserve, array items, `anyOf` branches, empty schema, non-mutation, pass-through of non-objects). - Updated existing `mastra.test.ts` / `mastra-ref.test.ts` assertions to reflect the relaxed output shape. - `pnpm test` → 64/64 passing. `pnpm typecheck` and `pnpm build` clean; eslint/prettier clean on changed files. --------- Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com> Co-authored-by: jkomyno <alberto@composio.dev>

Serhii Zghama committed Jun 24, 2026 at 23:03 UTC aaabf5e2a6998e700777fa38f7317698e658488c
7 files changed +481 -14
.changeset/mastra-output-schema-nullable.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/mastra': patch
3 +---
4 +
5 +Relax the Mastra provider output schema so real third-party API responses are no longer rejected by Mastra's output validation (which dropped the data and substituted an error). Before compilation the output schema is made lenient: every typed node becomes nullable, objects allow extra keys (`additionalProperties: true`), `enum`/`const` are widened to also admit `null`, and `required` is dropped (APIs omit unset fields rather than returning `null` for them). All of these only widen what validates, so previously-valid output is unaffected.
ts/packages/providers/mastra/src/index.ts
+13 -4
@@ -20,6 +20,7 @@ import {
20 } from '@composio/core';
21 import { applyCompatLayer } from '@mastra/schema-compat';
22 import { createTool } from '@mastra/core/tools';
23 +import { relaxOutputSchema } from './relax-output-schema';
24
25 export type MastraTool = ReturnType<typeof createTool>;
26
@@ -125,11 +126,19 @@ export class MastraProvider extends BaseAgenticProvider<
126 mode: 'jsonSchema',
127 });
128
129 + // Relax the output schema before compiling it: Composio's API-supplied
130 + // output schemas are strict (non-nullable primitives, additionalProperties
131 + // false), but third-party APIs return `null` for unset optional fields and
132 + // sometimes extra keys. Mastra validates results against this schema and
133 + // drops mismatching data, so without this every such response is truncated.
134 + // See https://github.com/ComposioHQ/composio/issues/3047.
135 const outputSchema = applyCompatLayer({
129 - schema: dereferenceJsonSchema(tool.outputParameters ?? {}, {
130 - onUnresolved: 'sentinel',
131 - onReplace,
132 - }),
136 + schema: relaxOutputSchema(
137 + dereferenceJsonSchema(tool.outputParameters ?? {}, {
138 + onUnresolved: 'sentinel',
139 + onReplace,
140 + })
141 + ),
142 compatLayers: [],
143 mode: 'jsonSchema',
144 });
ts/packages/providers/mastra/src/relax-output-schema.ts new
+127
@@ -0,0 +1,127 @@
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 +}
ts/packages/providers/mastra/test/mastra-ref.test.ts
+4 -1
@@ -91,7 +91,10 @@ describe('MastraProvider regression: $ref in JSON Schema', () => {
91 it('preserves type info from Draft-7 `definitions` on the output schema', () => {
92 const skuProp = findProperty(unwrapSchema(wrapped.outputSchema), 'sku');
93 expect(skuProp).toBeDefined();
94 - expect(skuProp?.type).toBe('string');
94 + // The output schema is relaxed to be nullable (issue #3047), so the
95 + // dereferenced `string` becomes `['string', 'null']` — the type info from
96 + // `definitions` is still preserved (not degraded to a permissive anyOf).
97 + expect(skuProp?.type).toEqual(['string', 'null']);
98 });
99
100 it('leaves no $ref in the produced schemas', () => {
ts/packages/providers/mastra/test/mastra.test.ts
+27 -9
@@ -40,6 +40,24 @@ vi.mock('@mastra/schema-compat', async () => {
40 };
41 });
42
43 +// Expected `originalSchema` for the standard mockTool output after the
44 +// leniency relaxation applied in wrapTool (issue #3047): typed nodes become
45 +// nullable and the object allows extra keys. All tools below spread `mockTool`,
46 +// so they share this output shape.
47 +const RELAXED_MOCK_OUTPUT_SCHEMA = {
48 + type: 'mock-zod-schema',
49 + originalSchema: {
50 + type: ['object', 'null'],
51 + additionalProperties: true,
52 + properties: {
53 + result: {
54 + type: ['string', 'null'],
55 + description: 'Test result',
56 + },
57 + },
58 + },
59 +};
60 +
61 describe('MastraProvider', () => {
62 let provider: MastraProvider;
63 let mockTool: Tool;
@@ -113,7 +131,7 @@ describe('MastraProvider', () => {
131 id: mockTool.slug,
132 description: mockTool.description,
133 inputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.inputParameters },
116 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
134 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
135 execute: expect.any(Function),
136 });
137
@@ -153,7 +171,7 @@ describe('MastraProvider', () => {
171 id: toolWithoutInputParams.slug,
172 description: toolWithoutInputParams.description,
173 inputSchema: { type: 'mock-zod-schema', originalSchema: {} },
156 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
174 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
175 execute: expect.any(Function),
176 });
177
@@ -197,7 +215,7 @@ describe('MastraProvider', () => {
215 id: toolWithoutDescription.slug,
216 description: '',
217 inputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.inputParameters },
200 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
218 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
219 execute: expect.any(Function),
220 });
221
@@ -308,14 +326,14 @@ describe('MastraProvider', () => {
326 id: mockTool.slug,
327 description: mockTool.description,
328 inputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.inputParameters },
311 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
329 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
330 execute: expect.any(Function),
331 });
332 expect(createTool).toHaveBeenCalledWith({
333 id: anotherTool.slug,
334 description: anotherTool.description,
335 inputSchema: { type: 'mock-zod-schema', originalSchema: anotherTool.inputParameters },
318 - outputSchema: { type: 'mock-zod-schema', originalSchema: anotherTool.outputParameters },
336 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
337 execute: expect.any(Function),
338 });
339 });
@@ -559,7 +577,7 @@ describe('MastraProvider', () => {
577 additionalProperties: false,
578 },
579 },
562 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
580 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
581 execute: expect.any(Function),
582 });
583 });
@@ -608,7 +626,7 @@ describe('MastraProvider', () => {
626 required: ['required_field'],
627 },
628 },
611 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
629 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
630 execute: expect.any(Function),
631 });
632 });
@@ -637,7 +655,7 @@ describe('MastraProvider', () => {
655 description: 'A string parameter',
656 },
657 },
640 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
658 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
659 execute: expect.any(Function),
660 });
661 });
@@ -657,7 +675,7 @@ describe('MastraProvider', () => {
675 id: toolWithoutInputParams.slug,
676 description: toolWithoutInputParams.description,
677 inputSchema: { type: 'mock-zod-schema', originalSchema: {} },
660 - outputSchema: { type: 'mock-zod-schema', originalSchema: mockTool.outputParameters },
678 + outputSchema: RELAXED_MOCK_OUTPUT_SCHEMA,
679 execute: expect.any(Function),
680 });
681 });
ts/packages/providers/mastra/test/output-validation.integration.test.ts new
+125
@@ -0,0 +1,125 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { applyCompatLayer, convertSchemaToZod } from '@mastra/schema-compat';
3 +import { relaxOutputSchema } from '../src/relax-output-schema';
4 +
5 +/**
6 + * Integration regression test for issue #3047.
7 + *
8 + * `mastra.test.ts` mocks `@mastra/schema-compat`, so it verifies *that*
9 + * `wrapTool` relaxes the output schema but never exercises the real validation.
10 + * This test runs the full production chain instead — the same one `wrapTool`
11 + * drives at tool-execution time:
12 + *
13 + * relaxOutputSchema → applyCompatLayer(mode: 'jsonSchema') → convertSchemaToZod → parse
14 + *
15 + * `convertSchemaToZod` is the JSON-Schema → Zod conversion Mastra performs
16 + * internally before `validateToolOutput` checks a tool result. The test proves
17 + * that the relaxation makes a real third-party API response (with `null`
18 + * optional fields and extra keys) survive validation instead of being dropped
19 + * and replaced by an error — and that no data is truncated in the process.
20 + *
21 + * See https://github.com/ComposioHQ/composio/issues/3047.
22 + */
23 +
24 +// A strict Composio-style output schema: optional fields typed as non-nullable
25 +// primitives, objects closed with `additionalProperties: false` — exactly the
26 +// shape the Composio API emits for connector tools.
27 +const STRICT_OUTPUT_SCHEMA = {
28 + type: 'object',
29 + additionalProperties: false,
30 + properties: {
31 + data: {
32 + type: 'object',
33 + additionalProperties: false,
34 + properties: {
35 + id: { type: 'string' },
36 + title: { type: 'string' },
37 + avatarUrl: { type: 'string' },
38 + description: { type: 'string' },
39 + assignee: {
40 + type: 'object',
41 + additionalProperties: false,
42 + properties: { name: { type: 'string' } },
43 + },
44 + },
45 + },
46 + },
47 +};
48 +
49 +// A realistic third-party response: `null` for unset optional fields plus an
50 +// unexpected extra key — what Linear / Notion / Jira / Slack actually return.
51 +const REAL_API_PAYLOAD = {
52 + data: {
53 + id: 'iss_123',
54 + title: 'Fix the thing',
55 + avatarUrl: null,
56 + description: null,
57 + assignee: null,
58 + unexpectedExtraKey: 'present',
59 + },
60 +};
61 +
62 +/** Mirror of the validation Mastra runs on a tool result. */
63 +function compileForValidation(schema: object) {
64 + const jsonSchema = applyCompatLayer({ schema, compatLayers: [], mode: 'jsonSchema' });
65 + return convertSchemaToZod(jsonSchema as object);
66 +}
67 +
68 +describe('Mastra output validation against real schema-compat (issue #3047)', () => {
69 + it('documents the bug: the strict schema rejects null optional fields', () => {
70 + const validator = compileForValidation(STRICT_OUTPUT_SCHEMA);
71 + const result = validator.safeParse(REAL_API_PAYLOAD);
72 + // Without the relaxation Mastra would drop this data and substitute an error.
73 + expect(result.success).toBe(false);
74 + });
75 +
76 + it('relaxed schema accepts the payload, preserving null values and extra keys', () => {
77 + const validator = compileForValidation(relaxOutputSchema(STRICT_OUTPUT_SCHEMA));
78 + const result = validator.safeParse(REAL_API_PAYLOAD);
79 +
80 + expect(result.success).toBe(true);
81 + // Nothing is truncated: nulls and the extra key survive untouched.
82 + expect(result.data).toEqual(REAL_API_PAYLOAD);
83 + });
84 +
85 + it('relaxed schema lets an enum field return null, but still rejects bogus values', () => {
86 + const schema = {
87 + type: 'object',
88 + additionalProperties: false,
89 + properties: { status: { type: 'string', enum: ['open', 'closed'] } },
90 + };
91 + const strict = compileForValidation(schema);
92 + const relaxed = compileForValidation(relaxOutputSchema(schema));
93 +
94 + expect(strict.safeParse({ status: null }).success).toBe(false); // the gap
95 + expect(relaxed.safeParse({ status: null }).success).toBe(true); // fixed
96 + expect(relaxed.safeParse({ status: 'open' }).success).toBe(true); // still valid
97 + expect(relaxed.safeParse({ status: 'nope' }).success).toBe(false); // still constrained
98 + });
99 +
100 + it('relaxed schema accepts a response that omits a required field', () => {
101 + const schema = {
102 + type: 'object',
103 + additionalProperties: false,
104 + required: ['id', 'title'],
105 + properties: { id: { type: 'string' }, title: { type: 'string' } },
106 + };
107 + const strict = compileForValidation(schema);
108 + const relaxed = compileForValidation(relaxOutputSchema(schema));
109 +
110 + expect(strict.safeParse({ id: 'iss_1' }).success).toBe(false); // the gap
111 + expect(relaxed.safeParse({ id: 'iss_1' }).success).toBe(true); // fixed
112 + });
113 +
114 + it('never narrows validation through a `not` keyword', () => {
115 + const schema = { not: { type: 'string' } }; // "must not be a string" — null is valid
116 + const strict = compileForValidation(schema);
117 + const relaxed = compileForValidation(relaxOutputSchema(schema));
118 +
119 + // Relaxing `not`'s subschema would make these previously-valid values fail.
120 + expect(strict.safeParse(null).success).toBe(true);
121 + expect(relaxed.safeParse(null).success).toBe(true); // still valid, not narrowed
122 + expect(relaxed.safeParse(42).success).toBe(true); // still valid
123 + expect(relaxed.safeParse('str').success).toBe(false); // constraint preserved
124 + });
125 +});
ts/packages/providers/mastra/test/relax-output-schema.test.ts new
+180
@@ -0,0 +1,180 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { relaxOutputSchema } from '../src/relax-output-schema';
3 +
4 +describe('relaxOutputSchema (issue #3047)', () => {
5 + it('adds "null" to a primitive type so API nulls validate', () => {
6 + expect(relaxOutputSchema({ type: 'string' })).toEqual({ type: ['string', 'null'] });
7 + });
8 +
9 + it('appends "null" to an existing type array without duplicating it', () => {
10 + expect(relaxOutputSchema({ type: ['string', 'number'] })).toEqual({
11 + type: ['string', 'number', 'null'],
12 + });
13 + expect(relaxOutputSchema({ type: ['string', 'null'] })).toEqual({
14 + type: ['string', 'null'],
15 + });
16 + });
17 +
18 + it('relaxes nested object properties, flips additionalProperties false → true, and drops required', () => {
19 + const input = {
20 + type: 'object',
21 + additionalProperties: false,
22 + properties: {
23 + avatarUrl: { type: 'string' },
24 + assignee: {
25 + type: 'object',
26 + additionalProperties: false,
27 + properties: { name: { type: 'string' } },
28 + },
29 + },
30 + required: ['avatarUrl'],
31 + };
32 +
33 + // `required` is dropped (API may omit `avatarUrl` entirely), nested objects
34 + // are relaxed the same way, and nothing else is altered.
35 + expect(relaxOutputSchema(input)).toEqual({
36 + type: ['object', 'null'],
37 + additionalProperties: true,
38 + properties: {
39 + avatarUrl: { type: ['string', 'null'] },
40 + assignee: {
41 + type: ['object', 'null'],
42 + additionalProperties: true,
43 + properties: { name: { type: ['string', 'null'] } },
44 + },
45 + },
46 + });
47 + });
48 +
49 + it('drops required so an omitted field still validates (issue #3047 gap)', () => {
50 + const input = {
51 + type: 'object',
52 + additionalProperties: false,
53 + required: ['id', 'name'],
54 + properties: { id: { type: 'string' }, name: { type: 'string' } },
55 + };
56 + expect(relaxOutputSchema(input)).toEqual({
57 + type: ['object', 'null'],
58 + additionalProperties: true,
59 + properties: { id: { type: ['string', 'null'] }, name: { type: ['string', 'null'] } },
60 + });
61 + });
62 +
63 + it('widens an enum to also admit null without dropping the other members', () => {
64 + expect(relaxOutputSchema({ type: 'string', enum: ['open', 'closed'] })).toEqual({
65 + type: ['string', 'null'],
66 + enum: ['open', 'closed', null],
67 + });
68 + // idempotent: an enum that already allows null is left as-is
69 + expect(relaxOutputSchema({ type: 'string', enum: ['open', null] })).toEqual({
70 + type: ['string', 'null'],
71 + enum: ['open', null],
72 + });
73 + });
74 +
75 + it('converts const into a nullable two-member enum', () => {
76 + expect(relaxOutputSchema({ const: 'fixed' })).toEqual({ enum: ['fixed', null] });
77 + });
78 +
79 + it('adds additionalProperties: true to an object that omits it', () => {
80 + expect(relaxOutputSchema({ type: 'object', properties: {} })).toEqual({
81 + type: ['object', 'null'],
82 + additionalProperties: true,
83 + properties: {},
84 + });
85 + });
86 +
87 + it('does not touch additionalProperties on non-object (primitive) nodes', () => {
88 + expect(relaxOutputSchema({ type: 'string' })).not.toHaveProperty('additionalProperties');
89 + });
90 +
91 + it('preserves and recurses into a schema-valued additionalProperties', () => {
92 + const input = {
93 + type: 'object',
94 + additionalProperties: { type: 'string' },
95 + };
96 + expect(relaxOutputSchema(input)).toEqual({
97 + type: ['object', 'null'],
98 + additionalProperties: { type: ['string', 'null'] },
99 + });
100 + });
101 +
102 + it('relaxes array item schemas', () => {
103 + const input = {
104 + type: 'array',
105 + items: {
106 + type: 'object',
107 + additionalProperties: false,
108 + properties: { id: { type: 'number' } },
109 + },
110 + };
111 + expect(relaxOutputSchema(input)).toEqual({
112 + type: ['array', 'null'],
113 + items: {
114 + type: ['object', 'null'],
115 + additionalProperties: true,
116 + properties: { id: { type: ['number', 'null'] } },
117 + },
118 + });
119 + });
120 +
121 + it('recurses into anyOf/oneOf/allOf branches', () => {
122 + const input = {
123 + anyOf: [{ type: 'string' }, { type: 'object', properties: { a: { type: 'boolean' } } }],
124 + };
125 + expect(relaxOutputSchema(input)).toEqual({
126 + anyOf: [
127 + { type: ['string', 'null'] },
128 + {
129 + type: ['object', 'null'],
130 + additionalProperties: true,
131 + properties: { a: { type: ['boolean', 'null'] } },
132 + },
133 + ],
134 + });
135 + });
136 +
137 + it('leaves a `not` subschema untouched so relaxation never narrows validation', () => {
138 + // `not` negates its subschema: relaxing the inner schema (making it
139 + // nullable) would *reject* values that were valid before (e.g. `null` under
140 + // `not: { type: 'string' }`), violating the only-widen invariant. The inner
141 + // schema must therefore be preserved verbatim, even when nested in an object
142 + // that is itself relaxed.
143 + expect(relaxOutputSchema({ not: { type: 'string' } })).toEqual({ not: { type: 'string' } });
144 + expect(
145 + relaxOutputSchema({
146 + type: 'object',
147 + additionalProperties: false,
148 + properties: { x: { not: { type: 'string' } } },
149 + })
150 + ).toEqual({
151 + type: ['object', 'null'],
152 + additionalProperties: true,
153 + properties: { x: { not: { type: 'string' } } },
154 + });
155 + });
156 +
157 + it('returns an empty schema unchanged (no type, no properties)', () => {
158 + expect(relaxOutputSchema({})).toEqual({});
159 + });
160 +
161 + it('does not mutate the input schema (including required/enum/const paths)', () => {
162 + const input = {
163 + type: 'object',
164 + additionalProperties: false,
165 + required: ['a'],
166 + properties: {
167 + a: { type: 'string', enum: ['x', 'y'] },
168 + b: { const: 'z' },
169 + },
170 + };
171 + const snapshot = JSON.parse(JSON.stringify(input));
172 + relaxOutputSchema(input);
173 + expect(input).toEqual(snapshot);
174 + });
175 +
176 + it('passes through non-object inputs untouched', () => {
177 + expect(relaxOutputSchema(null as unknown as object)).toBeNull();
178 + expect(relaxOutputSchema(undefined as unknown as object)).toBeUndefined();
179 + });
180 +});