Skip to content

feat: pretty-print JSONL text responses in mcpcurl #239

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
Apr 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions cmd/mcpcurl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
Expand All @@ -11,8 +12,6 @@ import (
"slices"
"strings"

"crypto/rand"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -161,7 +160,7 @@ func main() {
_ = rootCmd.MarkPersistentFlagRequired("stdio-server-cmd")

// Add global flag for pretty printing
rootCmd.PersistentFlags().Bool("pretty", true, "Pretty print MCP response (only for JSON responses)")
rootCmd.PersistentFlags().Bool("pretty", true, "Pretty print MCP response (only for JSON or JSONL responses)")

// Add the tools command to the root command
rootCmd.AddCommand(toolsCmd)
Expand Down Expand Up @@ -426,15 +425,26 @@ func printResponse(response string, prettyPrint bool) error {
// Extract text from content items of type "text"
for _, content := range resp.Result.Content {
if content.Type == "text" {
// Unmarshal the text content
var textContent map[string]interface{}
if err := json.Unmarshal([]byte(content.Text), &textContent); err != nil {
return fmt.Errorf("failed to parse text content: %w", err)
var textContentObj map[string]interface{}
err := json.Unmarshal([]byte(content.Text), &textContentObj)

if err == nil {
prettyText, err := json.MarshalIndent(textContentObj, "", " ")
if err != nil {
return fmt.Errorf("failed to pretty print text content: %w", err)
}
fmt.Println(string(prettyText))
continue
}

// Fallback parsing as JSONL
var textContentList []map[string]interface{}
if err := json.Unmarshal([]byte(content.Text), &textContentList); err != nil {
return fmt.Errorf("failed to parse text content as a list: %w", err)
}
// Pretty print the text content
prettyText, err := json.MarshalIndent(textContent, "", " ")
prettyText, err := json.MarshalIndent(textContentList, "", " ")
if err != nil {
return fmt.Errorf("failed to pretty print text content: %w", err)
return fmt.Errorf("failed to pretty print array content: %w", err)
}
fmt.Println(string(prettyText))
}
Expand Down