diff --git a/packages/agent/src/operation-extensions/read-asset.test.ts b/packages/agent/src/operation-extensions/read-asset.test.ts index e3e3e26c..684f2090 100644 --- a/packages/agent/src/operation-extensions/read-asset.test.ts +++ b/packages/agent/src/operation-extensions/read-asset.test.ts @@ -752,7 +752,7 @@ describe('read_asset agent tool', () => { assetId: 'doc-md', docConfig: { mode: 'text', startPage: 1, endPage: 2 }, }), - ).rejects.toThrow('startPage and endPage must be null when docConfig mode is "text"') + ).rejects.toThrow('startPage and endPage must be left out when docConfig mode is "text"') }) it('reads raw text in mode "text"', async () => { diff --git a/packages/agent/src/operation-tools.ts b/packages/agent/src/operation-tools.ts index 4555ac90..725056e6 100644 --- a/packages/agent/src/operation-tools.ts +++ b/packages/agent/src/operation-tools.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import type { TSchema } from 'typebox' import { Compile } from 'typebox/compile' import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core' +import { dropNullOptionals } from '@shumai/operations' import { getOperationsForSurface, runOperation, @@ -53,27 +54,13 @@ export function toToolParameters(op: Operation, extension?: AgentToolExtension): return schema as unknown as TSchema } -/** - * Models sometimes send `null` for optional parameters they don't want to set. Drop those - * so the input schema treats them as omitted; nulls for required fields still fail. - */ -export function dropNullOptionalFields(schema: z.ZodObject, params: unknown): unknown { - if (!params || typeof params !== 'object' || Array.isArray(params)) return params - const shape = schema.shape - return Object.fromEntries( - Object.entries(params).filter( - ([key, value]) => !(value === null && shape[key]?.safeParse(undefined).success), - ), - ) -} - /** Split agent-only parameters from the Operation input. */ export function splitAgentParams( op: Operation, extension: AgentToolExtension | undefined, params: unknown, ): { input: unknown; extra: Record } { - const cleaned = dropNullOptionalFields(toolInputSchema(op, extension), params) + const cleaned = dropNullOptionals(toolInputSchema(op, extension), params) if (!extension?.extraParameters || !cleaned || typeof cleaned !== 'object') { return { input: cleaned, extra: {} } } diff --git a/packages/api/src/mcp-server.test.ts b/packages/api/src/mcp-server.test.ts index 9e6821b7..d398bb23 100644 --- a/packages/api/src/mcp-server.test.ts +++ b/packages/api/src/mcp-server.test.ts @@ -85,6 +85,55 @@ describe('MCP server', () => { expect(annotations('list_assets')).toMatchObject({ readOnlyHint: true, idempotentHint: true }) }) + it('advertises input schemas without nullable types', async () => { + // Nullable types don't translate to every client's tool format (e.g. Gemini's) + for (const tool of (await client.listTools()).tools) { + const schema = JSON.stringify(tool.inputSchema) + expect(schema, tool.name).not.toMatch(/"type":\[/) + expect(schema, tool.name).not.toContain('"type":"null"') + } + }) + + it('treats null optional arguments as omitted, including nested ones', async () => { + vi.mocked(runOperation).mockResolvedValue({ + status: 'pending', + summary: 'Rendering is still in progress for "deck.pdf".', + asset: { id: 'doc-1', name: 'deck.pdf', kind: 'document', mediaType: 'application/pdf' }, + details: [], + images: [], + taskId: 'task-1', + retryAfterSeconds: 5, + }) + + const result = await client.callTool({ + name: 'read_asset', + arguments: { + assetId: 'doc-1', + annotationId: null, + videoConfig: null, + docConfig: { mode: 'pages', startPage: 1, endPage: null }, + inlineImages: null, + }, + }) + + expect(result.isError).toBeFalsy() + expect(runOperation).toHaveBeenCalledWith( + readAssetOp, + { userId: 'user1', via: 'mcp' }, + { assetId: 'doc-1', docConfig: { mode: 'pages', startPage: 1 } }, + ) + }) + + it('still rejects null for required arguments', async () => { + const result = await client.callTool({ + name: 'create_folder', + arguments: { parent: null, name: 'Renders' }, + }) + + expect(result.isError).toBe(true) + expect(runOperation).not.toHaveBeenCalled() + }) + it('does not expose agent-only capabilities', async () => { const names = (await client.listTools()).tools.map((t) => t.name) for (const agentOnly of ['bash', 'read_skill', 'download_asset', 'mcp']) { diff --git a/packages/api/src/mcp-server.ts b/packages/api/src/mcp-server.ts index 57ca4f3f..f9045fe8 100644 --- a/packages/api/src/mcp-server.ts +++ b/packages/api/src/mcp-server.ts @@ -1,6 +1,8 @@ import { Hono } from 'hono' import { createMcpHandler, McpServer, type CallToolResult } from '@modelcontextprotocol/server' +import type { z } from 'zod' import type { Prisma } from '@shumai/db' +import { dropNullOptionals } from '@shumai/operations' import { getOperationsForSurface, runOperation, type Operation } from '@shumai/core/src/operations' import { mcpExtensions, type McpToolExtension } from './mcp-extensions' import { assertWritableInDemoMode, describeOperationError } from './operation-support' @@ -19,6 +21,21 @@ export const MCP_SERVER_INSTRUCTIONS = [ 'if it returns status "pending", call get_asset_render with its taskId.', ].join(' ') +/** + * The tool's input schema, with `null` for optional arguments treated as omitted. The SDK + * validates arguments before calling the tool, so the nulls must be dropped here; the JSON + * Schema shown to clients is unchanged (optional, not nullable, which more clients support). + */ +function toolInputSchema(schema: z.ZodObject): Pick { + const standard = schema['~standard'] + return { + '~standard': { + ...standard, + validate: (value) => standard.validate(dropNullOptionals(schema, value)), + }, + } +} + /** Separate MCP-only arguments (declared by an extension) from the Operation input. */ function splitArgs( extension: McpToolExtension | undefined, @@ -78,9 +95,11 @@ export function buildMcpServer(userId: string): McpServer { { title: definition.title, description: definition.description, - inputSchema: extension?.extraInput - ? definition.input.extend(extension.extraInput.shape) - : definition.input, + inputSchema: toolInputSchema( + extension?.extraInput + ? definition.input.extend(extension.extraInput.shape) + : definition.input, + ), outputSchema: definition.output, annotations: { title: definition.title, diff --git a/packages/core/src/asset-read/readers/document.ts b/packages/core/src/asset-read/readers/document.ts index 50e57bf3..91a1561e 100644 --- a/packages/core/src/asset-read/readers/document.ts +++ b/packages/core/src/asset-read/readers/document.ts @@ -99,7 +99,7 @@ export const documentReader: AssetReader<'document'> = { } if (startPage !== null || endPage !== null) { throw badRequest( - 'startPage and endPage must be null when docConfig mode is "text". To inspect specific page numbers, use mode: "pages".', + 'startPage and endPage must be left out when docConfig mode is "text". To inspect specific page numbers, use mode: "pages".', ) } if (!isPlainTextAsset(asset.mediaTypeLower, asset.filenameLower)) { diff --git a/packages/core/src/asset-read/readers/readers.test.ts b/packages/core/src/asset-read/readers/readers.test.ts index 8638505e..3167b8db 100644 --- a/packages/core/src/asset-read/readers/readers.test.ts +++ b/packages/core/src/asset-read/readers/readers.test.ts @@ -150,11 +150,9 @@ describe('model3dReader', () => { } as unknown as PrismaJson.MediaInfo, }) - it('accepts null as "show the overview"', async () => { - expect(() => - model3dReader.validate(model, { degree: null }, { hasAnnotation: false }), - ).not.toThrow() - const plan = await model3dReader.plan(model, { degree: null }, noAnnotation) + it('shows the overview when no degree is given', async () => { + expect(() => model3dReader.validate(model, {}, { hasAnnotation: false })).not.toThrow() + const plan = await model3dReader.plan(model, {}, noAnnotation) expect(plan.status).toBe('ready') }) diff --git a/packages/operations/src/asset/read-asset.ts b/packages/operations/src/asset/read-asset.ts index fb86b276..9ad32f18 100644 --- a/packages/operations/src/asset/read-asset.ts +++ b/packages/operations/src/asset/read-asset.ts @@ -20,7 +20,6 @@ export const readerOptionSchemas = { degree: z .number() .int() - .nullable() .optional() .describe( 'Turntable rotation degree (integer: 0, 15, 30, ..., 345 in 15° increments) to inspect a specific angle of a 3D model. Leave it out to view the 4-view composite overview.', @@ -57,12 +56,10 @@ export const readerOptionSchemas = { ), startPage: z .number() - .nullable() .optional() .describe('Start page number (1-based, required when mode="pages"; omit for "text").'), endPage: z .number() - .nullable() .optional() .describe( `End page number (1-based, max ${MAX_RENDER_ITEMS} pages per call, required when mode="pages"; omit for "text").`, diff --git a/packages/operations/src/index.ts b/packages/operations/src/index.ts index f23201cd..7eef4bc2 100644 --- a/packages/operations/src/index.ts +++ b/packages/operations/src/index.ts @@ -1,6 +1,7 @@ export * from './define' export * from './schemas' export * from './registry' +export { dropNullOptionals } from './null-optionals' export { createFolder } from './asset/create-folder' export { deleteAsset } from './asset/delete-asset' export { listAssets } from './asset/list-assets' diff --git a/packages/operations/src/null-optionals.test.ts b/packages/operations/src/null-optionals.test.ts new file mode 100644 index 00000000..7772dcae --- /dev/null +++ b/packages/operations/src/null-optionals.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { dropNullOptionals } from './null-optionals' + +const schema = z.object({ + id: z.string(), + note: z.string().optional(), + config: z + .object({ + mode: z.enum(['a', 'b']), + start: z.number().optional(), + }) + .optional(), + tags: z.array(z.string()).optional(), +}) + +describe('dropNullOptionals', () => { + it('drops nulls for optional fields, including inside nested objects', () => { + expect( + dropNullOptionals(schema, { + id: 'x', + note: null, + config: { mode: 'a', start: null }, + tags: null, + }), + ).toEqual({ id: 'x', config: { mode: 'a' } }) + }) + + it('drops a null nested object when the object is optional', () => { + expect(dropNullOptionals(schema, { id: 'x', config: null })).toEqual({ id: 'x' }) + }) + + it('keeps nulls for required fields so validation still fails', () => { + const cleaned = dropNullOptionals(schema, { id: null, config: { mode: null } }) + expect(cleaned).toEqual({ id: null, config: { mode: null } }) + expect(schema.safeParse(cleaned).success).toBe(false) + }) + + it('leaves unknown keys and non-object values alone', () => { + expect(dropNullOptionals(schema, { id: 'x', other: null })).toEqual({ id: 'x', other: null }) + expect(dropNullOptionals(schema, null)).toBeNull() + expect(dropNullOptionals(schema, ['a'])).toEqual(['a']) + }) +}) diff --git a/packages/operations/src/null-optionals.ts b/packages/operations/src/null-optionals.ts new file mode 100644 index 00000000..f7bc4fd9 --- /dev/null +++ b/packages/operations/src/null-optionals.ts @@ -0,0 +1,29 @@ +import { z } from 'zod' + +/** Strip optional/default wrappers to reach an object schema, if the field is one. */ +function objectSchemaOf(schema: z.ZodType): z.ZodObject | undefined { + let current: z.ZodType = schema + while (current instanceof z.ZodOptional || current instanceof z.ZodDefault) { + current = current.unwrap() as z.ZodType + } + return current instanceof z.ZodObject ? current : undefined +} + +/** + * Models often send `null` for optional parameters they don't want to set, including inside + * nested config objects. Operation inputs are optional rather than nullable (nullable types + * don't translate to every model's tool format), so drop those nulls before validating: + * they are treated as omitted. Nulls for required fields are kept and still fail validation. + */ +export function dropNullOptionals(schema: z.ZodObject, value: unknown): unknown { + if (!value || typeof value !== 'object' || Array.isArray(value)) return value + const shape = schema.shape as Record + const result: Record = {} + for (const [key, field] of Object.entries(value)) { + const fieldSchema = shape[key] + if (field === null && fieldSchema?.safeParse(undefined).success) continue + const nested = fieldSchema && objectSchemaOf(fieldSchema) + result[key] = nested ? dropNullOptionals(nested, field) : field + } + return result +} diff --git a/packages/operations/src/registry.test.ts b/packages/operations/src/registry.test.ts index 6986f971..5de7e755 100644 --- a/packages/operations/src/registry.test.ts +++ b/packages/operations/src/registry.test.ts @@ -70,6 +70,18 @@ describe('operation registry', () => { }, ) + it.each(operationDefinitions.map((d) => [d.name, d] as const))( + '%s input schema has no nullable types', + (_name, definition) => { + // Tool formats like Gemini's function declarations (an OpenAPI subset) can't express + // `type: [..., "null"]` or a `null` branch, so inputs use optional fields instead. + // Surfaces drop nulls that models send for optional fields (dropNullOptionals). + const schema = JSON.stringify(z.toJSONSchema(definition.input, { io: 'input' })) + expect(schema).not.toMatch(/"type":\[/) + expect(schema).not.toContain('"type":"null"') + }, + ) + it('keeps legacy CLI invocations mapped', () => { const commands = operationDefinitions.map((d) => [ d.name,