Skip to content

Conversation

@pottekkat
Copy link
Collaborator

@pottekkat pottekkat commented May 8, 2025

Fixes #259

To prevent omitting boolean values when they are false, we can use a boolean pointer instead.

Ref: https://stackoverflow.com/questions/37756236/json-golang-boolean-omitempty

This PR fixes the issue but maybe it can be made more elegant with proper setter functions (like withReadOnlyHint() which could take in a bool instead of a *bool to abstract the implementation from the SDK users) I will let others comment on how this should be done or whether it should be done at all.

But the PR in its current form, fixes the issue.

See #260 (comment) and my review below on why these changes were made.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added a utility function to simplify creating boolean pointer values.
  • Refactor

    • Updated tool annotation fields to use pointer booleans, allowing omission of unset values in JSON.
    • Introduced individual functions to set each tool annotation separately.
    • Adjusted related test code to handle pointer boolean fields for tool annotations.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 8, 2025

"""

Walkthrough

The changes convert the boolean fields in the ToolAnnotation struct from bool to *bool, introduce a helper function to create boolean pointers, and update all relevant code and tests to use these pointers. This ensures explicit false values are preserved during JSON marshaling instead of being omitted.

Changes

Files/Paths Change Summary
mcp/tools.go Changed ToolAnnotation fields from bool to *bool and updated NewTool to use boolean pointers via a helper function. Added new individual setter functions for each annotation field alongside the existing bulk setter.
mcp/utils.go Added ToBoolPtr utility function to create *bool from bool.
client/inprocess_test.go, client/sse_test.go, server/server_test.go Updated test code to use mcp.ToBoolPtr() for ToolAnnotation fields and dereference pointers in assertions.

Assessment against linked issues

Objective Addressed Explanation
Allow ToolAnnotation struct to explicitly set and preserve false values in JSON output (#259)

Possibly related PRs

  • fix: tool annotation #165: Modifies test code related to tool annotations, similar to this PR’s updates in test setup and assertions for annotation hints.
  • new feat: tool annotation #158: Introduced ToolAnnotation with boolean fields and original bulk setter; this PR changes those fields to pointers and adds individual setters.
    """

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c6354a3 and e381bb1.

📒 Files selected for processing (3)
  • client/inprocess_test.go (2 hunks)
  • client/sse_test.go (3 hunks)
  • mcp/tools.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • client/inprocess_test.go
  • client/sse_test.go
  • mcp/tools.go
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 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.

Support

Need 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)

  • @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 generate sequence diagram to generate a sequence diagram of the changes in 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: 0

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

169-175: Successfully updated initialization to use pointer values

The initialization in NewTool now correctly uses the BoolPtr helper function to create pointer values for the boolean fields. This ensures consistent behavior with the updated struct definition.

However, consider adding a comment explaining why pointers are used for boolean fields to help future maintainers understand this design choice.

        Annotations: ToolAnnotation{
            Title:           "",
+           // Using pointer values to ensure false values are properly marshaled
            ReadOnlyHint:    BoolPtr(false),
            DestructiveHint: BoolPtr(true),
            IdempotentHint:  BoolPtr(false),
            OpenWorldHint:   BoolPtr(true),
        },

133-144: Consider adding comment explaining the reason for using pointers for boolean fields

While the implementation is correct, adding documentation about why pointer types are used would make the code more maintainable. This helps other developers understand the reasoning behind this design choice.

type ToolAnnotation struct {
    // Human-readable title for the tool
    Title string `json:"title,omitempty"`
+   // Using *bool instead of bool ensures that explicit false values
+   // are preserved during JSON marshaling with the omitempty tag
    // If true, the tool does not modify its environment
    ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
    // If true, the tool may perform destructive updates
    DestructiveHint *bool `json:"destructiveHint,omitempty"`
    // If true, repeated calls with same args have no additional effect
    IdempotentHint *bool `json:"idempotentHint,omitempty"`
    // If true, tool interacts with external entities
    OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}

133-144: Consider implementing setter methods for a better developer experience

As mentioned in the PR summary, implementing setter methods (e.g., withReadOnlyHint()) would provide a more elegant interface for SDK users. This would abstract away the pointer implementation details and improve the developer experience.

Consider adding the following methods to improve the API:

// WithReadOnlyHint sets whether the tool does not modify its environment
func WithReadOnlyHint(hint bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.ReadOnlyHint = BoolPtr(hint)
    }
}

// WithDestructiveHint sets whether the tool may perform destructive updates
func WithDestructiveHint(hint bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.DestructiveHint = BoolPtr(hint)
    }
}

// WithIdempotentHint sets whether repeated calls with the same args have no additional effect
func WithIdempotentHint(hint bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.IdempotentHint = BoolPtr(hint)
    }
}

// WithOpenWorldHint sets whether the tool interacts with external entities
func WithOpenWorldHint(hint bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.OpenWorldHint = BoolPtr(hint)
    }
}

This would allow users to configure tools with a cleaner API:

tool := NewTool("my-tool", 
    WithDescription("A tool that does something"),
    WithReadOnlyHint(true),
    WithIdempotentHint(true),
)

Also applies to: 169-175

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd1e1e8 and abac82d.

📒 Files selected for processing (5)
  • client/inprocess_test.go (2 hunks)
  • client/sse_test.go (3 hunks)
  • mcp/tools.go (2 hunks)
  • mcp/utils.go (1 hunks)
  • server/server_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
client/sse_test.go (1)
mcp/utils.go (1)
  • BoolPtr (780-782)
client/inprocess_test.go (1)
mcp/utils.go (1)
  • BoolPtr (780-782)
server/server_test.go (1)
mcp/utils.go (1)
  • BoolPtr (780-782)
mcp/tools.go (1)
mcp/utils.go (1)
  • BoolPtr (780-782)
🔇 Additional comments (8)
mcp/utils.go (1)

778-782: Good addition of a utility function for boolean pointers.

This is a clean implementation of a helper function that will ease the conversion from boolean values to boolean pointers, which is needed to properly marshal boolean fields with false values when using the omitempty JSON tag.

server/server_test.go (1)

873-877: Clean conversion to boolean pointers.

The test code has been properly updated to use mcp.BoolPtr() for all boolean hint fields in the ToolAnnotation struct. This change aligns with the fix for ensuring false values are correctly preserved during JSON marshaling.

client/sse_test.go (3)

8-9: Import reordering looks good.

The import statement for the transport package has been appropriately reordered to follow standard library imports.


31-35: Properly updated boolean fields to use pointers.

The test code has been correctly modified to use mcp.BoolPtr() for all boolean hint fields in the ToolAnnotation struct, ensuring false values are preserved during JSON marshaling.


115-119: Assertion code correctly dereferencing boolean pointers.

The test assertions have been properly updated to dereference the pointer values before comparison, allowing the tests to validate the boolean values correctly.

client/inprocess_test.go (2)

27-31: Properly updated boolean fields to use pointers.

The test code has been correctly modified to use mcp.BoolPtr() for all boolean hint fields in the ToolAnnotation struct, ensuring proper JSON marshaling behavior.


146-150: Assertion code correctly dereferencing boolean pointers.

The test assertions have been properly updated to dereference the pointer values before comparison, allowing the tests to validate the boolean values correctly.

mcp/tools.go (1)

133-144: Good solution for preserving explicit false values during JSON marshaling

The change from bool to *bool is an effective solution to ensure that false values are properly marshaled to JSON rather than being omitted. In Go, the omitempty tag causes fields with zero values (including false for booleans) to be omitted during JSON marshaling. By using pointers, explicit false values will be included in the JSON output.

Copy link
Collaborator

@rwjblue-glean rwjblue-glean left a comment

Choose a reason for hiding this comment

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

Hmm. Could we remove omitempty instead? Wouldn't that have the result of making sure the fields are emitted even if the values are false? If so, that seems like better ergonomics to the end user of the sdk (dealing with the boolean pointers is a tad annoying for consumers IMO).

Quick demo

@pottekkat
Copy link
Collaborator Author

@robert-jackson-glean The problem with removing the omitempty option is that if the users don't specify the annotation, it will automatically be set to false instead of not having that annotation at all, which would be undesired behaviour.

From my experience in using this SDK, I think that the SDK provides all the tools but it is up to the implementations to use the SDK as they want to adhere to the specification as they like. The SDK supports annotations, the MCP spec recommends annotations but it is up to the user to decide if they want to support every annotation.

In that sense, we should always allow users to not specify any annotation and not automatically set a false value if it is not specified.

BUT, I agree this is bad UX. I had suggested abstracting the pointer logic from the SDK users in the PR description:

This PR fixes the issue but maybe it can be made more elegant with proper setter functions (like withReadOnlyHint() which could take in a bool instead of a *bool to abstract the implementation from the SDK users) I will let others comment on how this should be done or whether it should be done at all.

I was waiting for some feedback and now I know for sure it is bad UX, I will abstract it out. I will add a new commit with this change and you can check if the UX is good.

Comment on lines 25 to 31
mcp.WithToolAnnotation(
"Test Tool Annotation Title",
true,
false,
true,
false,
),
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This will be the UX for SDK users. It hides the pointer implementation from the users and it is more or less the same UX as we have now.

This follows similar WithX functions like:

WithResourceCapabilities(true, true),
WithPromptCapabilities(true),
WithToolCapabilities(true),

Comment on lines +171 to +174
ReadOnlyHint: ToBoolPtr(false),
DestructiveHint: ToBoolPtr(true),
IdempotentHint: ToBoolPtr(false),
OpenWorldHint: ToBoolPtr(true),
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The ToBoolPtr helper function can be used for internal tests.

Comment on lines +779 to +782
// ToBoolPtr returns a pointer to the given boolean value
func ToBoolPtr(b bool) *bool {
return &b
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

ToBoolPtr is a more semantic name. This is fine IMO and is followed in other Go projects for the same reason, to distinguish between not specified and zero values.

https://stackoverflow.com/questions/54823690/why-does-kubernetes-internally-use-string-pointers-rather-than-strings

@rwjblue-glean
Copy link
Collaborator

Thanks for continuing to iterate on this with me!

I kinda prefer the more explicit creation of the struct fields (that we have today on master) over the current rendition of this PR (e.g. many positional params). I understand what you were going with in the current rendition in that it follows the same sort of pattern as some of our existing WithXYZ() methods that take a couple params already -- it's just soooo many params and if all you wanted to do was to set one of them it's still a bit annoying (it also makes reading the code harder without a language server -- since its roughly impossible to remember the order of all the true/false values).

In that light, let's go back to your first iteration. Though I'm not sure we actually need the ToBoolPtr helper (it seems a little more ergonomic to say ReadonlyHint: &true to me as it does ReadonlyHint: mcp.ToBoolPtr(true)). Then let's also add the With*Annotation helper methods that you originally alluded to (e.g. WithReadOnlyHintAnnotation &c -- see snippet just below) to make it really nice to build a tool with the right annotations:

// WithReadOnlyHintAnnotation sets the ReadOnlyHint field of the Tool's Annotations.
// If true, it indicates the tool does not modify its environment.
func WithReadOnlyHintAnnotation(value bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.ReadOnlyHint = &value
    }
}

// WithDestructiveHintAnnotation sets the DestructiveHint field of the Tool's Annotations.
// If true, it indicates the tool may perform destructive updates.
func WithDestructiveHintAnnotation(value bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.DestructiveHint = &value
    }
}

// WithIdempotentHintAnnotation sets the IdempotentHint field of the Tool's Annotations.
// If true, it indicates repeated calls with the same arguments have no additional effect.
func WithIdempotentHintAnnotation(value bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.IdempotentHint = &value
    }
}

// WithOpenWorldHintAnnotation sets the OpenWorldHint field of the Tool's Annotations.
// If true, it indicates the tool interacts with external entities.
func WithOpenWorldHintAnnotation(value bool) ToolOption {
    return func(t *Tool) {
        t.Annotations.OpenWorldHint = &value
    }
}

// WithTitleAnnotation sets the Title field of the Tool's Annotations.
// It provides a human-readable title for the tool.
func WithTitleAnnotation(title string) ToolOption {
    return func(t *Tool) {
        t.Annotations.Title = title
    }
}

(then we just need ot make sure to tweak NewTool to do Annotations: ToolAnnotation{} so the t.Annotations is not nil)


What do you think? Sorry for the back and forth on approach here

@pottekkat
Copy link
Collaborator Author

pottekkat commented May 11, 2025

it's just soooo many params and if all you wanted to do was to set one of them it's still a bit annoying

Yes, I agree. I originally planned to use the helper functions, but this would mean we have two different ways to set the annotations, i.e., directly through the struct and through the helper functions. That's why I thought about let's just pass these as arguments.

But yeah, too many params. Maybe I'm overthinking it and we should just add the helper functions. That's the only reasonable alternative I found.

Let me update the changes.

No problems with the back and forth at all. I needed help to think this through. And honestly, reviews have been really quick 🚀

@pottekkat
Copy link
Collaborator Author

Though I'm not sure we actually need the ToBoolPtr helper (it seems a little more ergonomic to say ReadonlyHint: &true to me as it does ReadonlyHint: mcp.ToBoolPtr(true)).

We still need to create something like ptrTrue = true and ptrFalse = false and reference their address &ptrTrue right? I thought the helper function makes it consistent?

Also the helper function will only be used internally and by someone not wanting to use the helper functions right?

Do you have any alternate ideas?

@rwjblue-glean rwjblue-glean merged commit eeb7070 into mark3labs:main May 11, 2025
3 checks passed
@rwjblue-glean
Copy link
Collaborator

Do you have any alternate ideas?

I was just thinking that it's just as easy for folks to type &false directly to make the pointer. It's definitely not a big deal.

@pottekkat
Copy link
Collaborator Author

I was just thinking that it's just as easy for folks to type &false directly to make the pointer.

Yes I understand but you can't directly get the address of a literal right? You still need a variable?

@rwjblue-glean
Copy link
Collaborator

Yes I understand but you can't directly get the address of a literal right? You still need a variable?

Ha! Not sure, I just assumed you could (without a variable).

@pottekkat pottekkat deleted the fix/bool-omitempty/259 branch May 11, 2025 17:51
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.

bug: ToolAnnotations cannot have false values

2 participants