Skip to content

feat: support creating tools using go-struct-style input schema #534

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 12, 2025

Conversation

Grivn
Copy link
Contributor

@Grivn Grivn commented Aug 7, 2025

Description

Feat #535

Since we’ve already implemented the output schema with structured content, I’m now working on defining the input schema in a similar style.

We can specify JSON Schema properties directly in our Go struct, such as required enum etc., and then use a helper like mcp.WithInputSchema[WeatherRequest]() to generate the input schema accordingly.

This enhancement will help developers maintain MCP services more effectively by enabling a consistent, structured approach to both input and output schemas.

Please help to review. Thanks a lot.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Additional Information

Summary by CodeRabbit

  • New Features

    • Tools can now accept structured input defined from native types, with automatic JSON schema generation and support for required fields, enums, ranges and defaults.
    • Added an option to supply raw JSON schemas directly when needed.
  • Documentation

    • Updated docs and examples to demonstrate structured input/output, typed handlers, and schema tag usage.
  • Tests

    • Added tests verifying automatic input-schema generation and tool serialization.

Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

Walkthrough

Adds support for specifying tool input schemas from Go struct types (generic WithInputSchema[T]) and raw JSON (WithRawInputSchema), updates examples and docs to use struct-based schemas, and introduces a unit test validating generated JSON input schemas. Some struct field tags were adjusted for schema constraints.

Changes

Cohort / File(s) Change Summary
SDK: input schema helpers
mcp/tools.go
Add WithInputSchema[T any]() ToolOption to generate JSON schema from a Go type (using invopop/jsonschema) and set Tool.RawInputSchema; add WithRawInputSchema(json.RawMessage) ToolOption to set raw input schema directly.
SDK: tests
mcp/tools_test.go
Add TestToolWithInputSchema to assert WithInputSchema produces and embeds an inputSchema JSON object with expected properties.
Examples: structured I/O
examples/structured_input_and_output/main.go, examples/structured_input_and_output/README.md
Introduce WeatherRequest struct and update struct field jsonschema tags (required, enum, constraints); replace manual mcp.WithString/WithNumber parameter specs with mcp.WithInputSchema[...]() usage across tools and examples; update server description.
Docs: tools page
www/docs/pages/servers/tools.mdx
Add a "Struct-Based Schema Definition" section demonstrating WithInputSchema/WithOutputSchema, typed handlers, schema tag usage, structured results, and a complete file-ops example (content appears duplicated in the diff).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related issues

Possibly related PRs

Suggested labels

type: enhancement, area: sdk

Suggested reviewers

  • ezynda3
  • dugenkui03

📜 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 b46b0d7 and e0adb40.

📒 Files selected for processing (1)
  • www/docs/pages/servers/tools.mdx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • www/docs/pages/servers/tools.mdx
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@Grivn Grivn force-pushed the main branch 3 times, most recently from 35c4a65 to 712822b Compare August 7, 2025 07:20
@Grivn Grivn changed the title feat: support structured content and input schema feat: support creating tools using go-struct-style input schema Aug 7, 2025
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: 3

🧹 Nitpick comments (1)
mcp/tools_test.go (1)

546-547: Fix incorrect comment referencing output schema.

The comment references "RawOutputSchema" but should reference "RawInputSchema" since this test is for input schema functionality.

Apply this diff to fix the comment:

-	// Check that RawOutputSchema was set
+	// Check that RawInputSchema was set
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1263146 and abb5cda.

📒 Files selected for processing (4)
  • examples/structured_input_and_output/README.md (2 hunks)
  • examples/structured_input_and_output/main.go (3 hunks)
  • mcp/tools.go (1 hunks)
  • mcp/tools_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • examples/structured_input_and_output/README.md
  • examples/structured_input_and_output/main.go
  • mcp/tools.go
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in the mark3labs/mcp-go project should handle both InputSchema and RawInputSchema consistently between MarshalJSON and UnmarshalJSON methods, even though the tools response from MCP server typically doesn't contain rawInputSchema.
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in mark3labs/mcp-go handles both InputSchema and RawInputSchema formats. When unmarshaling JSON, it first tries to parse into a structured ToolInputSchema format, and if that fails, it falls back to using the raw schema format, providing symmetry with the MarshalJSON method.
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.
Learnt from: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
📚 Learning: the tool struct in mark3labs/mcp-go handles both inputschema and rawinputschema formats. when unmars...
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in mark3labs/mcp-go handles both InputSchema and RawInputSchema formats. When unmarshaling JSON, it first tries to parse into a structured ToolInputSchema format, and if that fails, it falls back to using the raw schema format, providing symmetry with the MarshalJSON method.

Applied to files:

  • mcp/tools_test.go
📚 Learning: the tool struct in the mark3labs/mcp-go project should handle both inputschema and rawinputschema co...
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in the mark3labs/mcp-go project should handle both InputSchema and RawInputSchema consistently between MarshalJSON and UnmarshalJSON methods, even though the tools response from MCP server typically doesn't contain rawInputSchema.

Applied to files:

  • mcp/tools_test.go
📚 Learning: tool responses from the mcp server shouldn't contain rawinputschema, which is why the unmarshaljson ...
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.

Applied to files:

  • mcp/tools_test.go
📚 Learning: in go mcp server, servertool.tool field is only used for tool listing and indexing, not for tool exe...
Learnt from: floatingIce91
PR: mark3labs/mcp-go#401
File: server/server.go:1082-1092
Timestamp: 2025-06-23T11:10:42.948Z
Learning: In Go MCP server, ServerTool.Tool field is only used for tool listing and indexing, not for tool execution or middleware. During handleToolCall, only the Handler field is used, so dynamic tools don't need the Tool field populated.

Applied to files:

  • mcp/tools_test.go
📚 Learning: in the mcptest package, prefer returning errors from helper functions rather than calling t.fatalf()...
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Applied to files:

  • mcp/tools_test.go
📚 Learning: in mcp-go project, the maintainer prefers keeping builder pattern apis simple without excessive vali...
Learnt from: davidleitw
PR: mark3labs/mcp-go#451
File: mcp/tools.go:1192-1217
Timestamp: 2025-06-26T09:38:18.629Z
Learning: In mcp-go project, the maintainer prefers keeping builder pattern APIs simple without excessive validation for edge cases. The WithOutput* functions are designed to assume correct usage rather than defensive programming, following the principle of API simplicity over comprehensive validation.

Applied to files:

  • mcp/tools_test.go
🧬 Code Graph Analysis (1)
mcp/tools_test.go (1)
mcp/tools.go (3)
  • NewTool (658-680)
  • WithDescription (701-705)
  • WithInputSchema (709-735)
🔇 Additional comments (1)
mcp/tools_test.go (1)

541-544: Confirm required Tag Handling in Schema Generation

The invopop/jsonschema-based generator in WithInputSchema does recognize the ,required option on Go json tags and pushes those field names into the schema’s required array. Your test’s use of json:"name,required" is valid and aligns with both our examples and the schema library’s expectations.

No changes needed here—please disregard the original concern.

@leyou240
Copy link

leyou240 commented Aug 8, 2025

looking forward this feature

@ezynda3
Copy link
Contributor

ezynda3 commented Aug 11, 2025

@Grivn could you add some bit of documentation in www/docs as well?

Add comprehensive documentation for the new struct-based schema features
introduced in commit b46b0d7, including:
- Input schema definition using Go structs with WithInputSchema
- Output schema definition using WithOutputSchema
- Structured tool handlers with NewStructuredToolHandler
- Array output schemas
- Schema tags reference
- Complete file operations example with structured I/O

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@Grivn
Copy link
Contributor Author

Grivn commented Aug 12, 2025

@ezynda3 I’ve updated tools.mdx with the changes for struct-based schema. Please review when you have a chance. Thanks.

@ezynda3 ezynda3 merged commit 8a18f59 into mark3labs:main Aug 12, 2025
4 checks passed
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.

3 participants