MCPcopy Create free account
hub / github.com/modelcontextprotocol/typescript-sdk / validateToolOutput

Method validateToolOutput

src/server/mcp.ts:287–319  ·  view source on GitHub ↗

* Validates tool output against the tool's output schema.

(tool: RegisteredTool, result: CallToolResult | CreateTaskResult, toolName: string)

Source from the content-addressed store, hash-verified

285 * Validates tool output against the tool's output schema.
286 */
287 private async validateToolOutput(tool: RegisteredTool, result: CallToolResult | CreateTaskResult, toolName: string): Promise<void> {
288 if (!tool.outputSchema) {
289 return;
290 }
291
292 // Only validate CallToolResult, not CreateTaskResult
293 if (!('content' in result)) {
294 return;
295 }
296
297 if (result.isError) {
298 return;
299 }
300
301 if (!result.structuredContent) {
302 throw new McpError(
303 ErrorCode.InvalidParams,
304 `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`
305 );
306 }
307
308 // if the tool has an output schema, validate structured content
309 const outputObj = normalizeObjectSchema(tool.outputSchema) as AnyObjectSchema;
310 const parseResult = await safeParseAsync(outputObj, result.structuredContent);
311 if (!parseResult.success) {
312 const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
313 const errorMessage = getParseErrorMessage(error);
314 throw new McpError(
315 ErrorCode.InvalidParams,
316 `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`
317 );
318 }
319 }
320
321 /**
322 * Executes a tool handler (either regular or task-based).

Callers 1

Calls 3

normalizeObjectSchemaFunction · 0.85
safeParseAsyncFunction · 0.85
getParseErrorMessageFunction · 0.85

Tested by

no test coverage detected