feat: update MCP tools to structured output format with SDK v1.15.0#719
feat: update MCP tools to structured output format with SDK v1.15.0#719
Conversation
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThis update standardizes the response format for MCP tools by shifting from array-based string messages to structured object-based payloads with explicit Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant MCP Tool
participant Runtime Utils
Client->>MCP Tool: Invoke tool (e.g., read file, grep)
MCP Tool->>Runtime Utils: Build response (success/error)
alt Success
Runtime Utils->>MCP Tool: buildMcpToolSuccessResponse({ message, content, ... })
else Error
Runtime Utils->>MCP Tool: buildMcpToolErrorResponse(convertErrorToJson(error))
end
MCP Tool->>Client: Structured response (JSON string in content, structuredContent object)
Possibly related PRs
✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
|
Claude finished @yamadashy's task —— View job PR Review CompleteI've thoroughly reviewed this PR that updates MCP tools to structured output format with SDK v1.15.0. This is a well-executed refactoring that significantly improves the MCP tools' usability and maintainability. Todo List:
✅ Strengths and Positive Changes1. Excellent SDK IntegrationThe upgrade from
2. Robust Structured Output ImplementationThe new
3. Improved Error HandlingThe centralized
4. Enhanced Test CoverageThe test updates demonstrate excellent testing practices:
5. Better API DesignTools like
💡 Suggestions for Improvement1. Type Safety EnhancementIn // Current
type McpToolStructuredContent = { [p: string]: unknown } | undefined;
// Suggested
interface McpToolStructuredContent {
message?: string;
[key: string]: unknown;
}2. Error Response ConsistencyIn // Current
return buildMcpToolErrorResponse({
message: `Error: Output file with ID ${outputId} not found...`,
});
// Suggested
return buildMcpToolErrorResponse({
message: `Output file with ID ${outputId} not found...`,
details: { outputId, reason: 'FILE_NOT_FOUND' }
});3. Response Format DocumentationConsider adding JSDoc comments to the response builder functions documenting the expected structure: /**
* Creates a successful MCP tool response with structured content
* @param structuredContent - Object containing both machine-readable data and human-readable message
* @returns CallToolResult with both text and structured content
*/4. Validation EnhancementIn // Consider adding more context
return buildMcpToolErrorResponse({
message: `Start line (${startLine}) cannot be greater than end line (${endLine})`,
details: { startLine, endLine, validation: 'INVALID_RANGE' }
});🔍 Code Quality AssessmentArchitecture & Design ⭐⭐⭐⭐⭐
Type Safety ⭐⭐⭐⭐☆
Error Handling ⭐⭐⭐⭐⭐
Testing ⭐⭐⭐⭐⭐
Documentation ⭐⭐⭐⭐☆
🎯 Overall AssessmentThis PR represents a high-quality refactoring that:
The implementation follows the project's coding guidelines well, uses proper dependency injection for testability, and maintains the sub-250-line file size preference. ✅ Recommendation: APPROVEThis is a well-executed upgrade that significantly improves the MCP tools' usability and maintainability. The structured output format will make these tools much more valuable for AI integration scenarios. | |
There was a problem hiding this comment.
PR Summary
Major upgrade to MCP tools implementing structured JSON output format with @modelcontextprotocol/sdk v1.15.0, enhancing machine readability for AI model interactions.
- Replaced array-based responses with structured JSON objects containing
messageandcontentfields in all MCP tools - Centralized error handling with new
convertErrorToJsonutility replacingformatToolError - Added
McpToolStructuredContenttype insrc/mcp/mcpToolRuntime.tsfor improved type safety - Enhanced MCP server instructions for better AI workflow clarity
- Updated all test files to verify new JSON response formats while maintaining 685 passing tests
15 files reviewed, 8 comments
Edit PR Review Bot Settings | Greptile
There was a problem hiding this comment.
Summary of Changes
Hello @yamadashy, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request focuses on a significant architectural improvement for the Model Context Protocol (MCP) tools by transitioning them to a structured JSON output format, aligning with the @modelcontextprotocol/sdk v1.15.0. This change is designed to make tool responses more easily consumable by AI models, thereby enhancing their integration and overall utility. The update also includes a centralized approach to error handling, clearer instructions for LLMs, and a general uplift in type safety.
Highlights
- SDK Upgrade: Upgraded
@modelcontextprotocol/sdkfrom version 1.11.0 to 1.15.0, incorporating new features and dependencies for enhanced functionality. - Structured Output Format Adoption: All Model Context Protocol (MCP) tools now return responses in a structured JSON format. This includes both a human-readable text message and machine-readable structured content, significantly improving integration with and usability for AI models.
- Centralized Error Handling: A new utility function,
convertErrorToJson, has been introduced and adopted across all tools to provide consistent and standardized error responses, enhancing debugging and predictability. - Enhanced LLM Instructions: The MCP server instructions have been refined to be more practical and actionable for Large Language Models (LLMs), clearly explaining tool workflows (e.g.,
pack_codebase->read_repomix_output) and specific use cases. - Improved Type Safety: Replaced generic 'any' types with specific TypeScript types, particularly for structured content (
McpToolStructuredContent), which boosts code maintainability and reduces type-related errors. - Tool-Specific Output Enhancements:
grepRepomixOutputToolandreadRepomixOutputToolnow return richer structured data, including matches and formatted output. Error handling inpackCodebaseToolandpackRemoteRepositoryToolhas been updated, and property naming consistency was addressed in file system tools. - Comprehensive Test Coverage: All relevant MCP tool tests have been updated to validate the new structured JSON response format, ensuring the correctness and reliability of the changes across the board.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request is a significant and well-executed update to align the MCP tools with the new structured output format from SDK v1.15.0. The changes are consistent across the codebase, improving machine-readability for AI models, and the centralized error handling is a great enhancement for maintainability.
I have one piece of feedback regarding the implementation of the structured response for packing tools, which currently results in a nested JSON string. Addressing this will further improve the machine-readability of the tool's output, which is the primary goal of this PR.
Overall, this is excellent work on this significant refactoring.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #719 +/- ##
==========================================
+ Coverage 90.37% 90.40% +0.02%
==========================================
Files 99 99
Lines 5561 5710 +149
Branches 1186 1193 +7
==========================================
+ Hits 5026 5162 +136
- Misses 535 548 +13 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Deploying repomix with
|
| Latest commit: |
8ab5db2
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://a7715fc1.repomix.pages.dev |
| Branch Preview URL: | https://feat-mcp-structured-tool-out.repomix.pages.dev |
- Upgrade @modelcontextprotocol/sdk from 1.11.0 to 1.15.0 - Add structured content support to all MCP tool responses - Update error handling to use convertErrorToJson utility - Rename formatToolResponse to formatPackToolResponse for clarity - Fix property naming consistency (contents → content) - Update all tests to expect new JSON response format - Replace 'any' types with proper TypeScript types for better type safety 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
Make the server description more practical and action-oriented: - Add specific tool names (pack_codebase, read_repomix_output, etc.) - Include clear workflow (pack → read/search) - Mention concrete use cases (code reviews, documentation, bug investigation) - Highlight key features (AI-optimized, security scanning, compression) This helps LLMs understand exactly how to use the Repomix MCP tools effectively. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
The test was failing because McpServer now accepts two arguments: 1. Server configuration (name, version) 2. Server options (instructions) Updated the test expectation to match the new constructor call. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Change buildMcpToolSuccessResponse: message → description - Change buildMcpToolErrorResponse: message → errorMessage - Update convertErrorToJson to return errorMessage field - Update all tool implementations to use new field names - Update all test expectations to match new response format This provides better semantic clarity: - description: explanatory text for successful operations - errorMessage: specific error information for failures 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
Expand error details to include: - cause: error cause chain for nested errors - code: error code/errno for system errors - timestamp: ISO timestamp when error occurred - type: distinguish between Error objects and unknown types Benefits: - Better debugging with more context - Consistent error tracking across tools - Enhanced monitoring and logging capabilities - Support for Node.js system error codes 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Enhance McpToolStructuredContent type with proper base interface - Add comprehensive error response types for grep tool - Implement type guards instead of unsafe type assertions in tests - Handle JSON.stringify(undefined) edge case properly - Add validation for negative line numbers in readRepomixOutputTool - Extract MCP server instructions to named constant - Remove unsafe 'any' type usage in error handling 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Update all 7 MCP tool files from tool() to registerTool() API - Add structured outputSchema with Zod schemas for type safety - Reorganize tool configuration with inputSchema and annotations - Update test mocks to use registerTool instead of deprecated tool() - Maintain backward compatibility with result field in pack tools - Add comprehensive output schemas for better LLM integration 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
…rator - Extract input/output schemas to top-level constants for all MCP tools - Use z.object() for schema definitions with z.infer for type generation - Add satisfies operator for compile-time type checking on responses - Remove redundant interface definitions (GrepToolErrorResponse, etc) - Update test assertions to match new MCP SDK behavior - Maintain .shape property for MCP SDK compatibility This improves maintainability by centralizing schema definitions and leveraging TypeScript's type inference capabilities. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
d10131c to
ac5d251
Compare
Added GitHub repository analysis as a key use case to better describe the pack_remote_repository tool's capabilities for analyzing remote repositories. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
There was a problem hiding this comment.
Pull Request Overview
This PR upgrades the MCP tools to SDK v1.15.0, replacing free‐form text outputs with structured JSON responses and centralizing error handling.
- Switched from
mcpServer.tooltomcpServer.registerToolacross all tools, adding ZodinputSchema/outputSchemaand descriptive metadata. - Introduced
convertErrorToJsonfor uniform error serialization and updated all tools to return a single JSON‐encoded content block. - Refactored runtime utilities (
mcpToolRuntime.ts) to emit structured content viabuildMcpToolSuccessResponse/buildMcpToolErrorResponse.
Reviewed Changes
Copilot reviewed 16 out of 17 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| src/mcp/tools/readRepomixOutputTool.ts | Added Zod schemas, used registerTool, structured JSON outputs |
| src/mcp/tools/packCodebaseTool.ts | Introduced Zod schemas, centralized error handling, structured API |
| src/mcp/tools/packRemoteRepositoryTool.ts | Same as above for remote repo packaging |
| src/mcp/tools/grepRepomixOutputTool.ts | Added input/output schemas, unified JSON response format |
| src/mcp/tools/fileSystemReadFileTool.ts | Schema definitions, structured output, security checks |
| src/mcp/tools/fileSystemReadDirectoryTool.ts | Schema definitions, structured output |
| src/mcp/tools/mcpToolRuntime.ts | Renamed/streamlined response format functions, added convertErrorToJson |
| src/mcp/mcpServer.ts | Updated McpServer instantiation with instructions object |
| tests/mcp/tools/* and tests/mcp/mcpServer.test.ts | Updated to expect single JSON content and parse errorMessage/fields |
Comments suppressed due to low confidence (5)
src/mcp/tools/readRepomixOutputTool.ts:11
- The file uses
fs.accessandfs.readFilebut does not importfs. Addimport fs from 'node:fs/promises';at the top to enable file operations.
} from './mcpToolRuntime.js';
src/mcp/tools/packRemoteRepositoryTool.ts:12
- You define Zod schemas (
z.object(...)) but haven't importedz. Addimport { z } from 'zod';at the top.
} from './mcpToolRuntime.js';
src/mcp/tools/packCodebaseTool.ts:12
- This file uses Zod (
z.object(...)) but doesn't importz. Addimport { z } from 'zod';to enable schema definitions.
} from './mcpToolRuntime.js';
src/mcp/tools/fileSystemReadFileTool.ts:11
- The tool references
z,fs, andpathbut only importsloggerand runtime helpers. Addimport { z } from 'zod'; import fs from 'node:fs/promises'; import path from 'node:path';at the top.
const fileSystemReadFileInputSchema = z.object({
src/mcp/tools/fileSystemReadDirectoryTool.ts:5
- This file uses
fs.readdir,fs.stat, andpath.isAbsolutebut only importszandlogger. Addimport fs from 'node:fs/promises'; import path from 'node:path';at the top.
import { z } from 'zod';
| description: ` | ||
| 🎉 Successfully packed codebase!\nPlease review the metrics below and consider adjusting compress/includePatterns/ignorePatterns if the token count is too high and you need to reduce it before reading the file content. |
There was a problem hiding this comment.
[nitpick] The multiline description string starts with a leading newline, which introduces an unintended blank line in the output. Consider removing the initial \n or trimming whitespace.
| description: ` | |
| 🎉 Successfully packed codebase!\nPlease review the metrics below and consider adjusting compress/includePatterns/ignorePatterns if the token count is too high and you need to reduce it before reading the file content. | |
| description: `🎉 Successfully packed codebase!\nPlease review the metrics below and consider adjusting compress/includePatterns/ignorePatterns if the token count is too high and you need to reduce it before reading the file content. |
|
@claude please review |
|
Claude finished @yamadashy's task —— View job PR Review CompleteI've thoroughly reviewed this PR that updates MCP tools to structured output format with SDK v1.15.0. This is a well-executed refactoring that significantly improves the MCP tools' usability and maintainability. Todo List:
✅ Strengths and Positive Changes1. Excellent SDK IntegrationThe upgrade from
2. Robust Structured Output ImplementationThe new
3. Improved Error HandlingThe centralized
4. Enhanced Test CoverageThe test updates demonstrate excellent testing practices:
5. Better API DesignTools like
💡 Suggestions for Improvement1. Type Safety EnhancementIn // Current
type McpToolStructuredContent = { [p: string]: unknown } | undefined;
// Suggested
interface McpToolStructuredContent {
message?: string;
[key: string]: unknown;
}2. Error Response ConsistencyIn // Current
return buildMcpToolErrorResponse({
message: `Error: Output file with ID ${outputId} not found...`,
});
// Suggested
return buildMcpToolErrorResponse({
message: `Output file with ID ${outputId} not found...`,
details: { outputId, reason: 'FILE_NOT_FOUND' }
});3. Response Format DocumentationConsider adding JSDoc comments to the response builder functions documenting the expected structure: /**
* Creates a successful MCP tool response with structured content
* @param structuredContent - Object containing both machine-readable data and human-readable message
* @returns CallToolResult with both text and structured content
*/4. Validation EnhancementIn // Consider adding more context
return buildMcpToolErrorResponse({
message: `Start line (${startLine}) cannot be greater than end line (${endLine})`,
details: { startLine, endLine, validation: 'INVALID_RANGE' }
});🔍 Code Quality AssessmentArchitecture & Design ⭐⭐⭐⭐⭐
Type Safety ⭐⭐⭐⭐☆
Error Handling ⭐⭐⭐⭐⭐
Testing ⭐⭐⭐⭐⭐
Documentation ⭐⭐⭐⭐☆
🎯 Overall AssessmentThis PR represents a high-quality refactoring that:
The implementation follows the project's coding guidelines well, uses proper dependency injection for testability, and maintains the sub-250-line file size preference. ✅ Recommendation: APPROVEThis is a well-executed upgrade that significantly improves the MCP tools' usability and maintainability. The structured output format will make these tools much more valuable for AI integration scenarios. |
|
@claude Are there any regressions in the code? |
|
Claude finished @yamadashy's task —— View job Regression Analysis CompleteI've thoroughly analyzed the PR for potential regressions in the MCP tools migration to structured output format with SDK v1.15.0. Todo List:
Regression Analysis Summary✅ No Critical Regressions FoundThis is a well-executed migration with comprehensive test coverage. The changes are intentional architectural improvements rather than regressions. 🔄 Breaking Changes (By Design)The PR intentionally introduces breaking changes to align with MCP SDK v1.15.0: 1. Response Format Change
2. API Changes
3. Function Renames
📊 Test Coverage AnalysisStrengths:
Coverage Gaps (54 lines missing):Based on CodeCov report, the gaps are in:
Assessment: These appear to be edge cases and error handling paths, not core functionality regressions. 🔍 Potential Issues Identified1. Minor Type Safety Concern// mcpToolRuntime.ts:37
type McpToolStructuredContent = { [p: string]: unknown } | undefined;Issue: Could be more specific for better type safety 2. JSON-in-JSON Structure// formatPackToolResponse returns stringified JSON within structured content
result: JSON.stringify(jsonResult, null, 2)Issue: Results in nested JSON strings requiring double parsing 3. Error Response ConsistencySome error responses lack detailed structure: // Could be improved with more structured details
return buildMcpToolErrorResponse({
message: `Error: Output file with ID ${outputId} not found...`,
// Missing: details: { outputId, reason: 'FILE_NOT_FOUND' }
});Impact: Low - errors work but less machine-readable 🚀 Improvements Gained1. Enhanced AI Integration
2. Better Error Handling
3. Type Safety Improvements
4. SDK Compliance
📋 Recommended ActionsFor This PR:
For Future Consideration:
🎯 Final AssessmentThis PR represents a high-quality architectural upgrade with no functional regressions. The breaking changes are intentional and necessary for SDK v1.15.0 compatibility. The comprehensive test coverage and consistent implementation across all tools demonstrate thorough execution. The changes improve AI integration capabilities, type safety, and maintainability while preserving all existing functionality in the new structured format. |
This PR updates the MCP tools to use structured output format compatible with @modelcontextprotocol/sdk v1.15.0, providing better machine-readable responses for AI models.
Summary
Changes Made
Core Updates
McpToolStructuredContenttypeconvertErrorToJsonutilityTool Updates
message,matches, andformattedOutputmessageandprocessedContentMCP Server Improvements
Test Updates
Benefits
Compatibility
Checklist
npm run test- All 685 tests passingnpm run lint- No linting errors