Skip to content

Commit f7124ac

Browse files
committed
feat: add NewToolResultJSON
1 parent 9f16336 commit f7124ac

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

mcp/utils.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,24 @@ func NewToolResultText(text string) *CallToolResult {
253253
}
254254
}
255255

256+
// NewToolResultJSON creates a new CallToolResult with a JSON content.
257+
func NewToolResultJSON[T any](data T) (*CallToolResult, error) {
258+
b, err := json.Marshal(data)
259+
if err != nil {
260+
return nil, fmt.Errorf("unable to marshal JSON: %w", err)
261+
}
262+
263+
return &CallToolResult{
264+
Content: []Content{
265+
TextContent{
266+
Type: ContentTypeText,
267+
Text: string(b),
268+
},
269+
},
270+
StructuredContent: data,
271+
}, nil
272+
}
273+
256274
// NewToolResultStructured creates a new CallToolResult with structured content.
257275
// It includes both the structured content and a text representation for backward compatibility.
258276
func NewToolResultStructured(structured any, fallbackText string) *CallToolResult {

www/docs/pages/servers/advanced.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ func handleCreateUser(ctx context.Context, req mcp.CallToolRequest, input UserCr
130130
Status: "created",
131131
}
132132

133-
return mcp.NewToolResultJSON(output), nil
133+
return mcp.NewToolResultJSON(output)
134134
}
135135
```
136136

@@ -962,4 +962,4 @@ For complete sampling documentation, see **[Server Sampling Guide](/servers/adva
962962
## Next Steps
963963

964964
- **[Client Development](/clients)** - Learn to build MCP clients
965-
- **[Server Basics](/servers/basics)** - Review fundamental concepts
965+
- **[Server Basics](/servers/basics)** - Review fundamental concepts

www/docs/pages/transports/http.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ func handleStatelessTool(ctx context.Context, req mcp.CallToolRequest) (*mcp.Cal
494494
return nil, err
495495
}
496496

497-
return mcp.NewToolResultJSON(result), nil
497+
return mcp.NewToolResultJSON(result)
498498
}
499499

500500
// Use external storage for persistence
@@ -693,4 +693,4 @@ The headers are automatically populated by the transport layer and are available
693693

694694
- **[In-Process Transport](/transports/inprocess)** - Learn about embedded scenarios
695695
- **[Client Development](/clients)** - Build MCP clients for HTTP transport
696-
- **[Server Basics](/servers/basics)** - Review fundamental server concepts
696+
- **[Server Basics](/servers/basics)** - Review fundamental server concepts

0 commit comments

Comments
 (0)