Skip to content

Conversation

xinwo
Copy link
Contributor

@xinwo xinwo commented Feb 25, 2025

Add strong type to Content.
It is easier to use, I think.

Summary by CodeRabbit

These updates enhance internal processing for improved reliability and consistency in handling responses, ensuring a smoother experience.

  • Refactor

    • Streamlined content handling to enforce consistent and reliable tool and prompt responses.
    • Centralized the processing of responses, reducing redundant error management.
  • Tests

    • Updated validations to align with enhanced content structures and stricter type enforcement for improved testing robustness.

@xinwo xinwo changed the title change to strong content type [WIP]change to strong content type Feb 25, 2025
@xinwo xinwo marked this pull request as draft February 25, 2025 01:07
@xinwo xinwo marked this pull request as ready for review February 26, 2025 07:50
@xinwo xinwo changed the title [WIP]change to strong content type change to strong content type Feb 26, 2025
@ezynda3 ezynda3 self-requested a review March 2, 2025 09:27
@ezynda3 ezynda3 marked this pull request as draft March 2, 2025 09:31
@ezynda3 ezynda3 marked this pull request as ready for review March 2, 2025 09:31
Copy link
Contributor

coderabbitai bot commented Mar 2, 2025

Walkthrough

The pull request refactors the way JSON responses and content types are handled across the project. Inline JSON unmarshalling has been replaced with calls to centralized parsing functions, and generic interface types have been updated to a new, specific Content interface. These changes span client methods, tests, server examples, and core types and utilities in the mcp package, promoting stricter type safety and a more streamlined control flow.

Changes

File(s) Change Summary
client/sse.go, client/stdio.go Removed inline JSON unmarshalling in GetPrompt and CallTool methods. Now delegates parsing to mcp.ParseGetPromptResult and mcp.ParseCallToolResult.
client/sse_test.go, server/ser..._test.go Updated the Content field type in CallToolResult from []interface{} to []mcp.Content for improved type safety.
examples/everything/main.go Modified all handle*Tool methods to return a consistent Content type ([]mcp.Content) rather than a generic slice.
mcp/prompts.go, mcp/tools.go Changed the Content fields from using a generic type (interface{} or []interface{}) to the specific Content type. Removed the local EmbeddedResource struct from prompts.go.
mcp/types.go Introduced a new Content interface and implemented it with TextContent, ImageContent, and a new EmbeddedResource type.
mcp/utils.go Updated function signatures to require the new Content type, and added helper functions (ExtractString, ExtractMap, ParseContent) along with new parsing functions: ParseGetPromptResult and ParseCallToolResult.

Sequence Diagram(s)

sequenceDiagram
    participant Client as SSEMCPClient
    participant Parser as mcp.ParseGetPromptResult
    participant Util as ParseContent
    Client->>Parser: Invoke GetPrompt(...)
    Parser->>Util: Parse raw JSON content
    Util-->>Parser: Return structured Content
    Parser-->>Client: Return GetPromptResult
Loading
sequenceDiagram
    participant Client as SSEMCPClient
    participant Parser as mcp.ParseCallToolResult
    participant Util as ParseContent
    Client->>Parser: Invoke CallTool(...)
    Parser->>Util: Parse raw JSON content
    Util-->>Parser: Return structured Content
    Parser-->>Client: Return CallToolResult
Loading

Poem

I'm a bunny hopping through the code,
Parsing changes lighten my abode,
JSON and Content now dance in a line,
Clean and structured—simply divine!
With every hop, bugs start to fade,
In this refined code glade 🐰🌸!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
mcp/utils.go (3)

310-310: Consider aligning resource content usage with the new Content interface.
Currently, NewReadResourceResult still leverages []interface{}{ TextResourceContents{...} }. If TextResourceContents qualifies as a Content type or could be made to implement Content, you may want to make it consistent with the rest of the code by returning []Content.


370-377: Verify silent fallback for missing or non-string data.
ExtractString returns "" whenever the key does not exist or is not a string. This may mask errors if the caller expects a non-empty value.


379-386: Confirm behavior for missing or invalid map data.
ExtractMap returns nil if the specified key is absent or not a map, potentially hiding misconfigurations. Ensure this is intended and properly handled downstream.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8d90a0 and d783f8f.

📒 Files selected for processing (9)
  • client/sse.go (2 hunks)
  • client/sse_test.go (1 hunks)
  • client/stdio.go (2 hunks)
  • examples/everything/main.go (5 hunks)
  • mcp/prompts.go (1 hunks)
  • mcp/tools.go (1 hunks)
  • mcp/types.go (3 hunks)
  • mcp/utils.go (8 hunks)
  • server/server_test.go (2 hunks)
🔇 Additional comments (25)
mcp/tools.go (1)

28-28: Improved type safety for Content field

The change from []interface{} to []Content enforces that only valid content types (TextContent, ImageContent, or EmbeddedResource) can be stored in this field, which enhances type safety and reduces potential runtime errors.

client/sse_test.go (1)

28-33: Test updated to use stronger typing

Test implementation properly updated to use the new mcp.Content interface type instead of generic interfaces, maintaining consistency with the production code changes.

mcp/types.go (4)

588-590: Good design for Content interface

Creating a marker interface with a simple isContent() method is a clean approach to establish type constraints while allowing for different concrete implementations.


601-601: TextContent implements Content interface

Proper implementation of the marker method to satisfy the Content interface.


614-614: ImageContent implements Content interface

Proper implementation of the marker method to satisfy the Content interface.


616-627: Well-designed EmbeddedResource type

The EmbeddedResource type is a good addition that enhances the content type system, providing a way to embed resource contents directly in responses. The implementation properly satisfies the Content interface.

mcp/prompts.go (1)

80-81: Enhanced type safety for PromptMessage

Changing from interface{} to the specific Content interface type ensures that only valid content types can be assigned to the Content field, improving type safety and maintainability.

client/stdio.go (2)

391-391: Improved type safety through centralized response parsing

This change replaces inline JSON unmarshalling with a call to mcp.ParseGetPromptResult(), centralizing the parsing logic and error handling. This enhances type safety by ensuring consistent parsing across client implementations.


420-420: Improved type safety through centralized response parsing

Similar to the GetPrompt method, this change replaces inline JSON unmarshalling with a call to mcp.ParseCallToolResult(), ensuring consistent parsing behavior and error handling.

server/server_test.go (1)

697-697: Strong type implementation for Content

Changing from []interface{} to []mcp.Content improves type safety by ensuring that the Content field only contains values that implement the Content interface. This aligns with the PR's objective of strengthening content type safety.

client/sse.go (2)

465-465: Improved type safety through centralized response parsing

This change replaces inline JSON unmarshalling with a call to mcp.ParseGetPromptResult(), which centralizes the parsing logic and error handling. This promotes consistent behavior across client implementations.


494-494: Improved type safety through centralized response parsing

Similar to the GetPrompt method, this change replaces inline JSON unmarshalling with a call to mcp.ParseCallToolResult(), promoting consistent behavior and error handling across client implementations.

examples/everything/main.go (5)

283-283: Strong typing for Content in tool results

Updating the Content field from []interface{} to []mcp.Content improves type safety and ensures that only valid content types are returned by the handler.


304-304: Strong typing for Content in tool results

Consistent with the pattern, changing to []mcp.Content ensures type safety for the handleAddTool function's return value.


333-333: Strong typing for Content in tool results

Updated the Content field to use the safer []mcp.Content type for the notification tool handler.


376-376: Strong typing for Content in tool results

Changed the Content field to use []mcp.Content for the long running operation tool handler, ensuring type safety and consistency.


415-415: Strong typing for Content in tool results

Updated the Content type for the image tool handler, maintaining consistency with the strongly typed Content interface pattern established throughout the codebase.

mcp/utils.go (8)

3-6: Imports look good.
No issues here. The addition of encoding/json and fmt is appropriate for the new parsing and formatting logic.


185-185: Good move to stronger typing.
Switching from interface{} to Content for the NewPromptMessage function signature helps enforce type safety and consistency across the codebase.


220-227: No concerns with text content array initialization.
Using []Content{...} here aligns well with the new strong-typed approach.


233-241: Consistent error flagging.
Creating a text content array and setting IsError = true is a clear way to indicate errors in tool results.


246-257: Excellent usage of combined text + image content.
Enforcing []Content aligns with the strong type approach for tool results.


266-277: Resource-based content array looks consistent.
Embedding both text and resource content is handled cleanly with the new []Content type.


434-494: Role validation may omit other valid roles.
Currently, roles other than "assistant" and "user" generate an error. Check if you need to handle additional roles such as "system" or custom roles.


496-545: Centralized tool result parsing looks clean.
This function properly defers to ParseContent for each item and handles errors gracefully, aligning well with the new strong type design.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants