Skip to content

Conversation

tylergannon
Copy link
Contributor

@tylergannon tylergannon commented Mar 2, 2025

Existing LLM projects will have already developed JSON Schemas to define their tool functions.

Some LLM projects use libraries such as invopop/jsonschema, to build JSON Schemas automatically.

This change honors the existing Options-based mechanism for building schemas, while opening a door to allow the use of JSON Schemas defined elsewhere.

In so doing, users of this package are better enabled to validate the parity between Tool JSON schemas and the Go structs that receive the argument.

Let me know if you'd prefer a different approach, etc. Your implementation is the best in class so far as I can see in the Golang world. I'd love to see what your road map looks like, in hopes of contributing in places where the goals align with what my primary project is doing.

Summary by CodeRabbit

  • New Features

    • Enhanced tool configuration by supporting an alternative JSON schema input method.
    • Improved error messaging to prevent configuration conflicts when multiple schema inputs are provided.
  • Tests

    • Added comprehensive tests to verify the new configuration approach and robust error handling.

Existing LLM projects will have already developed JSON Schemas
to define their tool functions.

Some LLM projects use libraries such as invopop/jsonschema,
to build JSON Schemas automatically.

This change honors the existing Options-based mechanism for
building schemas, while opening a door to allow the use of
JSON Schemas defined elsewhere.

In so doing, users of this package are better enabled to
validate the parity between Tool JSON schemas and the Go
structs that receive the argument.
Copy link
Contributor

coderabbitai bot commented Mar 2, 2025

Walkthrough

This pull request updates the tool schema handling in the mcp package. The Tool struct now supports an alternative raw JSON schema input with a new RawInputSchema field. The JSON marshaling logic has been updated to select the appropriate schema or return an error when both schema types are provided simultaneously. Additionally, a new constructor function for raw schemas was introduced, and corresponding tests were added to validate both correct serialization and schema conflict error handling.

Changes

File(s) Change Summary
mcp/tools.go - Introduced a new error variable errToolSchemaConflict.
- Updated the Tool struct: hidden InputSchema from JSON and added RawInputSchema.
- Implemented MarshalJSON to handle serialization and conflict detection.
- Added NewToolWithRawSchema constructor for initializing tools with a raw JSON schema.
mcp/tools_test.go - Added TestToolWithBothSchemasError to verify error handling when both schemas are set.
- Added TestToolWithRawSchema to validate tool creation and JSON serialization with a raw schema using the assert package.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Tool
    Client->>Tool: Create tool instance (using NewToolWithRawSchema or standard constructor)
    Client->>Tool: Call MarshalJSON()
    alt Both InputSchema and RawInputSchema provided
        Tool-->>Client: Return errToolSchemaConflict error
    else RawInputSchema is provided
        Tool-->>Client: Return JSON serialized with RawInputSchema
    else
        Tool-->>Client: Return JSON serialized with InputSchema
    end
Loading

Poem

I'm a rabbit with code so keen,
Hopping through changes in the scene,
Raw schemas gleam in my moonlit night,
Errors vanish as I leap with might,
Tests ensure my bounds delight;
In code and hops, everything's just right!

✨ 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: 0

🧹 Nitpick comments (4)
mcp/tools_test.go (2)

19-20: Consider adding validation of initial successful marshal.

You're correctly checking that the initial marshaling succeeds, but consider asserting on the structure of the marshaled JSON to ensure it contains the expected schema before adding the conflicting raw schema.

-	_, err := json.Marshal(tool)
-	assert.Nil(t, err)
+	initialJSON, err := json.Marshal(tool)
+	assert.Nil(t, err)
+	
+	// Verify initial schema was properly included
+	var initialResult map[string]interface{}
+	err = json.Unmarshal(initialJSON, &initialResult)
+	assert.NoError(t, err)
+	assert.Contains(t, initialResult, "inputSchema")

44-46: Consider testing NewToolWithRawSchema's error handling.

While you're testing the successful case, consider also testing how NewToolWithRawSchema handles invalid JSON in the raw schema parameter. This would ensure robust error handling for malformed schemas.

+func TestToolWithInvalidRawSchema(t *testing.T) {
+	// Create an invalid raw schema
+	rawSchema := json.RawMessage(`{invalid json`)
+
+	// Create a tool with invalid raw schema
+	tool := NewToolWithRawSchema("invalid-schema-tool", "Invalid schema", rawSchema)
+
+	// Marshal to JSON should fail
+	_, err := json.Marshal(tool)
+	assert.Error(t, err)
+}
mcp/tools.go (2)

82-104: Robust schema conflict detection in MarshalJSON.

The implementation correctly handles schema selection and conflict detection. When both schemas are present, it returns a descriptive error that includes the tool name.

Consider adding a check for the case where neither schema is provided, which could provide a more helpful error or default behavior:

} else if t.InputSchema.Type != "" {
	// Use the structured InputSchema
	m["inputSchema"] = t.InputSchema
+} else {
+	// Neither schema is provided, using a default empty object schema
+	m["inputSchema"] = ToolInputSchema{
+		Type:       "object",
+		Properties: make(map[string]interface{}),
+	}
}

144-159: Well-documented constructor for raw schema tools.

The constructor is well-documented with a clear NOTE about incompatibility with ToolOption. The implementation is straightforward and correctly sets up a tool with a raw schema.

Consider adding validation to ensure the provided raw schema is valid JSON:

func NewToolWithRawSchema(name, description string, schema json.RawMessage) Tool {
+	// Validate that the schema is valid JSON
+	var js interface{}
+	if err := json.Unmarshal(schema, &js); err != nil {
+		// Since we can't return an error from this constructor, log a warning
+		// or consider panicking in development builds
+		// For now, we'll continue but the MarshalJSON will fail later
+	}
+
	tool := Tool{
		Name:           name,
		Description:    description,
		RawInputSchema: schema,
	}

	return tool
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e6fe09 and f10a1bb.

📒 Files selected for processing (2)
  • mcp/tools.go (3 hunks)
  • mcp/tools_test.go (1 hunks)
🔇 Additional comments (4)
mcp/tools_test.go (2)

10-31: Thorough test case for schema conflict detection.

This test effectively verifies that an error is returned when both schema types are used simultaneously. It creates a realistic scenario where a developer might add both schema types accidentally.


33-75: Comprehensive test for raw schema functionality.

This test thoroughly validates the raw schema functionality by checking both the marshaling process and the resulting structure. The assertions properly verify that all components of the schema are correctly preserved.

mcp/tools.go (2)

9-9: Well-defined error with clear message.

This error message clearly communicates the problem to developers when both schema types are used simultaneously.


75-78: Clear implementation of dual schema support.

The implementation correctly hides both schema fields from direct JSON marshaling, allowing the custom MarshalJSON method to handle the schema logic.

@tylergannon
Copy link
Contributor Author

Notes

I gave consideration to alternative routes that involve changing the mcp.Tool.InputSchema field into something more generic like json.Marshaler or any. But in all cases, it would involve some more complex validation logic and it felt like they all opened up the plausible likelihood of developers misunderstanding the API and, e.g., mixing WithRawSchema() and WithBoolean(), etc.

Landed on this proposal not out of affinity towards the internal representation but out of the simplicity of the changes and the maintaining a fairly straightforward API.

@ezynda3
Copy link
Contributor

ezynda3 commented Mar 2, 2025

I like this idea. Also I don't have a detailed roadmap at the moment. The main goal at the moment is to have feature parity with the official SDKs like TS and Python. Any and all PRs are welcome in that regard.

@ezynda3 ezynda3 merged commit 86c2947 into mark3labs:main Mar 2, 2025
2 checks passed
@xinwo xinwo mentioned this pull request Mar 4, 2025
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