mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 17:58:23 +00:00
fix(mcp): make tool input schemas portable to single-type dialects
Nullable inputs were emitted as `type: ["number", "null"]` (or a `null` anyOf branch), which clients that map tool schemas onto an OpenAPI-style subset (e.g. Gemini function declarations) may reject. - Make read_asset's startPage, endPage, and degree optional instead of nullable. - Move null handling into a shared dropNullOptionals helper in @shumai/operations that also strips nulls inside nested config objects. The agent uses it, and the MCP server applies it before the SDK validates arguments, so models that send null keep working. - Test that no Operation input schema (and no listed MCP tool) uses a nullable type.
This commit is contained in:
@@ -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 () => {
|
||||
|
||||
@@ -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<string, unknown> } {
|
||||
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: {} }
|
||||
}
|
||||
|
||||
@@ -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']) {
|
||||
|
||||
@@ -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<z.ZodObject, '~standard'> {
|
||||
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,
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
|
||||
@@ -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").`,
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'])
|
||||
})
|
||||
})
|
||||
@@ -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<string, z.ZodType>
|
||||
const result: Record<string, unknown> = {}
|
||||
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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user