@evantahler/mcpx 0.15.9 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,7 +29,7 @@ mcpx exec <server> <tool> '<json args>'
29
29
  mcpx exec <server> <tool> -f params.json
30
30
  ```
31
31
 
32
- Output is JSON when piped. Use `--json` to force JSON output in any context — prefer this when you need to parse results programmatically.
32
+ Output is JSON by default. Use `--json` to force JSON output in any context — prefer this when you need to parse results programmatically. Use `--format text` to extract just the text content (stripping the MCP protocol wrapper), or `--format markdown` for rich terminal rendering.
33
33
 
34
34
  ## Rules
35
35
 
@@ -38,6 +38,8 @@ Output is JSON when piped. Use `--json` to force JSON output in any context —
38
38
  - Use `mcpx search -k` for exact name matching
39
39
  - Pipe results through `jq` when you need to extract specific fields
40
40
  - Use `--json` when parsing output programmatically (automatic when piped, but explicit is safer)
41
+ - Use `--format text` to extract plain text from tool results (strips MCP protocol wrapper)
42
+ - Use `--format markdown` for rich terminal-rendered output with colors and formatting
41
43
  - Use `-v` for verbose debugging (HTTP details + JSON-RPC protocol messages) if an exec fails unexpectedly
42
44
  - Use `-l debug` to see all server log messages, or `-l error` for errors only
43
45
 
@@ -149,15 +151,16 @@ mcpx deauth <server> # remove stored auth
149
151
 
150
152
  ## Global flags
151
153
 
152
- | Flag | Purpose |
153
- | ------------------------- | -------------------------------------------------------- |
154
- | `-j, --json` | Force JSON output (default when piped) |
155
- | `-v, --verbose` | Show HTTP details and JSON-RPC protocol messages |
156
- | `-d, --with-descriptions` | Include tool descriptions in list output |
157
- | `-c, --config <path>` | Specify config file location |
158
- | `-N, --no-interactive` | Decline server elicitation requests (for scripted usage) |
159
- | `-S, --show-secrets` | Show full auth tokens in verbose output (unmasked) |
160
- | `-l, --log-level <level>` | Minimum server log level to display (default: `warning`) |
154
+ | Flag | Purpose |
155
+ | --------------------------- | -------------------------------------------------------- |
156
+ | `-j, --json` | Force JSON output (default when piped) |
157
+ | `-F, --format <format>` | Output format: `json`, `text`, or `markdown` |
158
+ | `-v, --verbose` | Show HTTP details and JSON-RPC protocol messages |
159
+ | `-d, --with-descriptions` | Include tool descriptions in list output |
160
+ | `-c, --config <path>` | Specify config file location |
161
+ | `-N, --no-interactive` | Decline server elicitation requests (for scripted usage) |
162
+ | `-S, --show-secrets` | Show full auth tokens in verbose output (unmasked) |
163
+ | `-l, --log-level <level>` | Minimum server log level to display (default: `warning`) |
161
164
 
162
165
  ## `add` options
163
166
 
@@ -29,12 +29,17 @@ mcpx exec <server> <tool> '<json args>'
29
29
  mcpx exec <server> <tool> -f params.json
30
30
  ```
31
31
 
32
+ Output is JSON by default. Use `--json` to force JSON output in any context — prefer this when you need to parse results programmatically. Use `--format text` to extract just the text content (stripping the MCP protocol wrapper), or `--format markdown` for rich terminal rendering.
33
+
32
34
  ## Rules
33
35
 
34
36
  - Always search before executing — don't assume tool names exist
35
37
  - Always inspect the schema before executing — validate you have the right arguments
36
38
  - Use `mcpx search -k` for exact name matching
37
39
  - Pipe results through `jq` when you need to extract specific fields
40
+ - Use `--json` when parsing output programmatically (automatic when piped, but explicit is safer)
41
+ - Use `--format text` to extract plain text from tool results (strips MCP protocol wrapper)
42
+ - Use `--format markdown` for rich terminal-rendered output with colors and formatting
38
43
  - Use `-v` for verbose debugging (HTTP details + JSON-RPC protocol messages) if an exec fails unexpectedly
39
44
  - Use `-l debug` to see all server log messages, or `-l error` for errors only
40
45
 
@@ -58,16 +63,22 @@ mcpx exec github search_repositories '{"query":"mcp"}' \
58
63
  # Read args from stdin
59
64
  echo '{"path":"./README.md"}' | mcpx exec filesystem read_file
60
65
 
61
- # Pipe from a file
62
- cat params.json | mcpx exec server tool
63
-
64
66
  # Read args from a file with --file flag
65
67
  mcpx exec filesystem read_file -f params.json
66
68
  ```
67
69
 
68
- ## 4. Long-running tools (Tasks)
70
+ ## Troubleshooting
71
+
72
+ - **"Not authenticated" / 401 error** → Run `mcpx auth <server>` to start the OAuth flow
73
+ - **Exec timeout** → Use `-v` to see where it stalls; set `MCP_TIMEOUT=<seconds>` to increase the timeout (default: 1800)
74
+ - **Search returns no results** → Try `mcpx search -k "*keyword*"` for glob matching, or `mcpx index` to rebuild the search index
75
+ - **Missing or stale tools** → Run `mcpx index` to rebuild; any command that connects to a server also auto-updates the index
76
+ - **Server won't connect** → Run `mcpx ping <server>` to check connectivity; use `-v` for protocol-level details
77
+ - **Auth token expired** → Run `mcpx auth <server> -r` to force a token refresh
78
+
79
+ ## Long-running tools (Tasks)
69
80
 
70
- Some tools support async execution via MCP Tasks. mcpx auto-detects this and uses task-augmented execution when available.
81
+ Some tools support async execution via MCP Tasks. mcpx auto-detects this.
71
82
 
72
83
  ```bash
73
84
  # Default: waits for the task to complete, showing progress
@@ -76,90 +87,122 @@ mcpx exec my-server long_running_tool '{"input": "data"}'
76
87
  # Return immediately with a task handle (for scripting/polling)
77
88
  mcpx exec my-server long_running_tool '{"input": "data"}' --no-wait
78
89
 
79
- # Check task status
90
+ # Check task status / retrieve result / cancel
80
91
  mcpx task get my-server <taskId>
81
-
82
- # Retrieve the result once complete
83
92
  mcpx task result my-server <taskId>
84
-
85
- # List all tasks on a server
86
- mcpx task list my-server
87
-
88
- # Cancel a running task
89
93
  mcpx task cancel my-server <taskId>
94
+ mcpx task list my-server
90
95
  ```
91
96
 
92
- For tools that don't support tasks, `exec` works exactly as before.
93
-
94
- ## 5. Elicitation (Server-Requested Input)
95
-
96
- Some servers request user input mid-operation (e.g., confirmations, auth flows). mcpx handles this automatically:
97
-
98
- ```bash
99
- # Interactive — prompts appear in the terminal
100
- mcpx exec my-server deploy_tool '{"target": "staging"}'
101
- # Server requests input: Confirm deployment
102
- # *Confirm [y/n]: y
103
-
104
- # Non-interactive — decline all elicitation (for scripts/CI)
105
- mcpx exec my-server deploy_tool '{"target": "staging"}' --no-interactive
97
+ ## Elicitation (Server-Requested Input)
106
98
 
107
- # JSON mode read/write elicitation as JSON via stdin/stdout
108
- echo '{"action":"accept","content":{"confirm":true}}' | \
109
- mcpx exec my-server deploy_tool '{"target": "staging"}' --json
110
- ```
99
+ Some servers request user input mid-operation. mcpx handles this automatically in interactive mode. Use `-N` / `--no-interactive` to decline all elicitation (for scripts/CI), or `--json` to handle elicitation programmatically via stdin/stdout.
111
100
 
112
101
  ## Authentication
113
102
 
114
- Some HTTP servers require OAuth. If you see an "Not authenticated" error:
115
-
116
103
  ```bash
117
- mcpx auth <server> # authenticate via browser
118
- mcpx auth <server> -s # check token status and TTL
119
- mcpx auth <server> -r # force token refresh
120
- mcpx deauth <server> # remove stored auth
104
+ mcpx auth <server> # authenticate via browser
105
+ mcpx auth <server> -s # check token status and TTL
106
+ mcpx auth <server> -r # force token refresh
107
+ mcpx auth <server> --no-index # authenticate without rebuilding search index
108
+ mcpx deauth <server> # remove stored auth
121
109
  ```
122
110
 
123
111
  ## Available commands
124
112
 
125
113
  | Command | Purpose |
126
114
  | -------------------------------------- | --------------------------------- |
127
- | `mcpx` | List all servers and tools |
128
- | `mcpx servers` | List servers (name, type, detail) |
129
- | `mcpx -d` | List with descriptions |
130
- | `mcpx info <server>` | Server overview (version, capabilities, tools) |
131
- | `mcpx info <server> <tool>` | Show tool schema |
132
- | `mcpx exec <server>` | List tools for a server |
133
- | `mcpx exec <server> <tool> '<json>'` | Execute a tool |
134
- | `mcpx exec <server> <tool> -f file` | Execute with args from file |
135
- | `mcpx search "<query>"` | Search tools (keyword + semantic) |
136
- | `mcpx search -k "<pattern>"` | Keyword/glob search only |
137
- | `mcpx search -q "<query>"` | Semantic search only |
138
- | `mcpx search -n <number> "<query>"` | Limit number of results (default: 10) |
139
- | `mcpx index` | Build/rebuild search index |
140
- | `mcpx index -i` | Show index status |
141
- | `mcpx auth <server>` | Authenticate with OAuth |
142
- | `mcpx auth <server> -s` | Check token status and TTL |
115
+ | `mcpx` | List all servers and tools |
116
+ | `mcpx servers` | List servers (name, type, detail) |
117
+ | `mcpx -d` | List with descriptions |
118
+ | `mcpx info <server>` | Server overview (version, capabilities, tools) |
119
+ | `mcpx info <server> <tool>` | Show tool schema |
120
+ | `mcpx exec <server>` | List tools for a server |
121
+ | `mcpx exec <server> <tool> '<json>'` | Execute a tool |
122
+ | `mcpx exec <server> <tool> -f file` | Execute with args from file |
123
+ | `mcpx search "<query>"` | Search tools (keyword + semantic) |
124
+ | `mcpx search -k "<pattern>"` | Keyword/glob search only |
125
+ | `mcpx search -q "<query>"` | Semantic search only |
126
+ | `mcpx search -n <number> "<query>"` | Limit number of results (default: 10) |
127
+ | `mcpx index` | Build/rebuild search index |
128
+ | `mcpx index -i` | Show index status |
129
+ | `mcpx auth <server>` | Authenticate with OAuth |
130
+ | `mcpx auth <server> -s` | Check token status and TTL |
143
131
  | `mcpx auth <server> -r` | Force token refresh |
144
- | `mcpx deauth <server>` | Remove stored authentication |
145
- | `mcpx ping` | Check connectivity to all servers |
146
- | `mcpx ping <server> [server2...]` | Check specific server(s) |
147
- | `mcpx add <name> --command <cmd>` | Add a stdio MCP server |
148
- | `mcpx add <name> --url <url>` | Add an HTTP MCP server |
149
- | `mcpx add <name> --url <url> --transport sse` | Add a legacy SSE server |
150
- | `mcpx remove <name>` | Remove an MCP server |
151
- | `mcpx skill install --claude` | Install mcpx skill for Claude |
152
- | `mcpx skill install --cursor` | Install mcpx rule for Cursor |
153
- | `mcpx resource` | List all resources across servers |
154
- | `mcpx resource <server>` | List resources for a server |
155
- | `mcpx resource <server> <uri>` | Read a specific resource |
156
- | `mcpx prompt` | List all prompts across servers |
157
- | `mcpx prompt <server>` | List prompts for a server |
158
- | `mcpx prompt <server> <name> '<json>'` | Get a specific prompt |
159
- | `mcpx exec <server> <tool> --no-wait` | Execute as async task, return handle |
160
- | `mcpx exec <server> <tool> --ttl <ms>` | Set task TTL (default: 60000) |
161
- | `mcpx -N exec <server> <tool> ...` | Decline elicitation (non-interactive) |
162
- | `mcpx task list <server>` | List tasks on a server |
163
- | `mcpx task get <server> <taskId>` | Get task status |
164
- | `mcpx task result <server> <taskId>` | Retrieve completed task result |
165
- | `mcpx task cancel <server> <taskId>` | Cancel a running task |
132
+ | `mcpx auth <server> --no-index` | Authenticate without rebuilding index |
133
+ | `mcpx deauth <server>` | Remove stored authentication |
134
+ | `mcpx ping` | Check connectivity to all servers |
135
+ | `mcpx ping <server> [server2...]` | Check specific server(s) |
136
+ | `mcpx add <name> --command <cmd>` | Add a stdio MCP server |
137
+ | `mcpx add <name> --url <url>` | Add an HTTP MCP server |
138
+ | `mcpx remove <name>` | Remove an MCP server |
139
+ | `mcpx skill install --claude` | Install mcpx skill for Claude |
140
+ | `mcpx skill install --cursor` | Install mcpx rule for Cursor |
141
+ | `mcpx resource` | List all resources across servers |
142
+ | `mcpx resource <server>` | List resources for a server |
143
+ | `mcpx resource <server> <uri>` | Read a specific resource |
144
+ | `mcpx prompt` | List all prompts across servers |
145
+ | `mcpx prompt <server>` | List prompts for a server |
146
+ | `mcpx prompt <server> <name> '<json>'` | Get a specific prompt |
147
+ | `mcpx task list <server>` | List tasks on a server |
148
+ | `mcpx task get <server> <taskId>` | Get task status |
149
+ | `mcpx task result <server> <taskId>` | Retrieve completed task result |
150
+ | `mcpx task cancel <server> <taskId>` | Cancel a running task |
151
+
152
+ ## Global flags
153
+
154
+ | Flag | Purpose |
155
+ | --------------------------- | -------------------------------------------------------- |
156
+ | `-j, --json` | Force JSON output (default when piped) |
157
+ | `-F, --format <format>` | Output format: `json`, `text`, or `markdown` |
158
+ | `-v, --verbose` | Show HTTP details and JSON-RPC protocol messages |
159
+ | `-d, --with-descriptions` | Include tool descriptions in list output |
160
+ | `-c, --config <path>` | Specify config file location |
161
+ | `-N, --no-interactive` | Decline server elicitation requests (for scripted usage) |
162
+ | `-S, --show-secrets` | Show full auth tokens in verbose output (unmasked) |
163
+ | `-l, --log-level <level>` | Minimum server log level to display (default: `warning`) |
164
+
165
+ ## `add` options
166
+
167
+ | Flag | Purpose |
168
+ | -------------------------- | -------------------------------------- |
169
+ | `--command <cmd>` | Command to run (stdio server) |
170
+ | `--args <a1,a2,...>` | Comma-separated arguments |
171
+ | `--env <KEY=VAL,...>` | Comma-separated environment variables |
172
+ | `--cwd <dir>` | Working directory for the command |
173
+ | `--url <url>` | Server URL (HTTP server) |
174
+ | `--header <Key:Value>` | HTTP header (repeatable) |
175
+ | `--transport <type>` | Transport: `sse` or `streamable-http` |
176
+ | `--allowed-tools <t1,t2>` | Comma-separated allowed tool patterns |
177
+ | `--disabled-tools <t1,t2>` | Comma-separated disabled tool patterns |
178
+ | `-f, --force` | Overwrite if server already exists |
179
+ | `--no-auth` | Skip automatic OAuth after adding |
180
+ | `--no-index` | Skip rebuilding the search index |
181
+
182
+ ## `remove` options
183
+
184
+ | Flag | Purpose |
185
+ | ------------- | ------------------------------------------------ |
186
+ | `--keep-auth` | Don't remove stored auth credentials |
187
+ | `--dry-run` | Show what would be removed without changing files |
188
+
189
+ ## `skill install` options
190
+
191
+ | Flag | Purpose |
192
+ | ----------- | ------------------------------------------ |
193
+ | `--claude` | Install skill for Claude Code |
194
+ | `--cursor` | Install rule for Cursor |
195
+ | `--global` | Install to global location (`~/`) |
196
+ | `--project` | Install to project location (default) |
197
+ | `-f, --force` | Overwrite if file already exists |
198
+
199
+ ## Environment variables
200
+
201
+ | Variable | Purpose | Default |
202
+ | ----------------- | --------------------------- | ---------- |
203
+ | `MCP_CONFIG_PATH` | Config directory path | `~/.mcpx/` |
204
+ | `MCP_TIMEOUT` | Request timeout (seconds) | `1800` |
205
+ | `MCP_CONCURRENCY` | Parallel server connections | `5` |
206
+ | `MCP_MAX_RETRIES` | Retry attempts | `3` |
207
+ | `MCP_STRICT_ENV` | Error on missing `${VAR}` | `true` |
208
+ | `MCP_DEBUG` | Enable debug output | `false` |
package/README.md CHANGED
@@ -107,6 +107,7 @@ mcpx search -n 5 "manage pull requests"
107
107
  | `-v, --verbose` | Show HTTP details and JSON-RPC protocol messages |
108
108
  | `-S, --show-secrets` | Show full auth tokens in verbose output (unmasked) |
109
109
  | `-j, --json` | Force JSON output (default when piped) |
110
+ | `-F, --format <format>` | Output format: `json`, `text`, or `markdown` |
110
111
  | `-N, --no-interactive` | Decline server elicitation requests (for scripted usage) |
111
112
  | `-l, --log-level <level>` | Minimum server log level to display (default: `warning`) |
112
113
 
@@ -495,7 +496,36 @@ mcpx info github | jq '.tools[].name'
495
496
  mcpx info github --json
496
497
  ```
497
498
 
498
- Tool results are always JSON, designed for chaining:
499
+ ### Output Formats (`--format`)
500
+
501
+ Tool results (`exec`, `task result`) support three output formats via the global `--format` / `-F` flag:
502
+
503
+ | Format | Description |
504
+ | ---------- | ----------------------------------------------------------------------- |
505
+ | `json` | Full MCP protocol response as JSON (default) |
506
+ | `text` | Extract text from content blocks, strip protocol wrapper |
507
+ | `markdown` | Extract text and render with rich terminal formatting (colors, borders) |
508
+
509
+ ```bash
510
+ # Default JSON output — full MCP response with content array
511
+ mcpx exec github search_repositories '{"query":"mcp"}'
512
+
513
+ # Text — just the content, no protocol wrapper
514
+ mcpx exec github search_repositories '{"query":"mcp"}' --format text
515
+
516
+ # Markdown — rich terminal rendering with colors and formatting
517
+ mcpx exec github search_repositories '{"query":"mcp"}' -F markdown
518
+ ```
519
+
520
+ The `text` format extracts text from MCP content blocks and strips the protocol wrapper. If the text contains JSON, it's pretty-printed. Non-text content (images, resources) gets descriptive placeholders.
521
+
522
+ The `markdown` format extracts text the same way, then renders it through Bun's built-in markdown parser with ANSI styling — headings, bold/italic, code blocks with borders, colored links, and bullet lists.
523
+
524
+ For other commands (`list`, `info`, `search`), `--format json` forces JSON output and `--format text`/`--format markdown` use the existing human-friendly formatting.
525
+
526
+ ### Chaining tool results
527
+
528
+ Tool results are JSON by default, designed for chaining:
499
529
 
500
530
  ```bash
501
531
  # Search repos and read the first result
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evantahler/mcpx",
3
- "version": "0.15.9",
3
+ "version": "0.16.1",
4
4
  "description": "A command-line interface for MCP servers. curl for MCP.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.ts CHANGED
@@ -25,6 +25,7 @@ program
25
25
  .option("-c, --config <path>", "config directory path")
26
26
  .option("-d, --with-descriptions", "include tool descriptions in output")
27
27
  .option("-j, --json", "force JSON output")
28
+ .option("-F, --format <format>", "output format (json, text, markdown)")
28
29
  .option("-v, --verbose", "show HTTP details and JSON-RPC protocol messages")
29
30
  .option("-S, --show-secrets", "show full auth tokens in verbose output")
30
31
  .option("-N, --no-interactive", "decline server elicitation requests")
@@ -56,7 +57,14 @@ const cliArgs = process.argv.slice(2);
56
57
  let firstCommand: string | undefined;
57
58
  for (let i = 0; i < cliArgs.length; i++) {
58
59
  const a = cliArgs[i];
59
- if (a === "-c" || a === "--config" || a === "-l" || a === "--log-level") {
60
+ if (
61
+ a === "-c" ||
62
+ a === "--config" ||
63
+ a === "-l" ||
64
+ a === "--log-level" ||
65
+ a === "-F" ||
66
+ a === "--format"
67
+ ) {
60
68
  i++; // skip the option's value argument
61
69
  continue;
62
70
  }
package/src/context.ts CHANGED
@@ -2,7 +2,7 @@ import type { Command } from "commander";
2
2
  import { loadConfig, type LoadConfigOptions } from "./config/loader.ts";
3
3
  import { ServerManager } from "./client/manager.ts";
4
4
  import type { Config } from "./config/schemas.ts";
5
- import type { FormatOptions } from "./output/formatter.ts";
5
+ import { type FormatOptions, type OutputFormat, VALID_FORMATS } from "./output/formatter.ts";
6
6
  import { logger } from "./output/logger.ts";
7
7
  import { ENV, DEFAULTS } from "./constants.ts";
8
8
 
@@ -35,6 +35,13 @@ export async function getContext(program: Command): Promise<AppContext> {
35
35
  // Commander's --no-interactive sets opts.interactive = false (default true)
36
36
  const noInteractive = opts.interactive === false;
37
37
 
38
+ const formatFlag = opts.format as string | undefined;
39
+ if (formatFlag && !VALID_FORMATS.includes(formatFlag as OutputFormat)) {
40
+ console.error(`error: Invalid format "${formatFlag}". Use: ${VALID_FORMATS.join(", ")}`);
41
+ process.exit(1);
42
+ }
43
+ const format = formatFlag as OutputFormat | undefined;
44
+
38
45
  const manager = new ServerManager({
39
46
  servers: config.servers,
40
47
  configDir: config.configDir,
@@ -55,6 +62,7 @@ export async function getContext(program: Command): Promise<AppContext> {
55
62
  verbose,
56
63
  showSecrets,
57
64
  logLevel,
65
+ format,
58
66
  };
59
67
 
60
68
  logger.configure(formatOptions);
@@ -3,14 +3,24 @@ import { isInteractive } from "./formatter.ts";
3
3
 
4
4
  /**
5
5
  * Format output with automatic JSON/interactive branching.
6
- * In non-interactive mode, returns JSON.stringify of jsonData.
7
- * In interactive mode, calls interactiveFn() for formatted output.
6
+ * When --format is explicitly set, it takes precedence:
7
+ * json JSON.stringify of jsonData
8
+ * text or markdown → interactiveFn() (already well-formatted for non-exec commands)
9
+ * Otherwise falls back to the existing auto-detection:
10
+ * non-interactive → JSON, interactive → formatted text.
8
11
  */
9
12
  export function formatOutput(
10
13
  jsonData: unknown,
11
14
  interactiveFn: () => string,
12
15
  options: FormatOptions,
13
16
  ): string {
17
+ if (options.format) {
18
+ if (options.format === "json") {
19
+ return JSON.stringify(jsonData, null, 2);
20
+ }
21
+ // text and markdown use the interactive formatter for non-exec commands
22
+ return interactiveFn();
23
+ }
14
24
  if (!isInteractive(options)) {
15
25
  return JSON.stringify(jsonData, null, 2);
16
26
  }
@@ -6,12 +6,17 @@ import type { SearchResult } from "../search/index.ts";
6
6
  import { formatOutput } from "./format-output.ts";
7
7
  import { formatTable } from "./format-table.ts";
8
8
 
9
+ export const VALID_FORMATS = ["json", "text", "markdown"] as const;
10
+
11
+ export type OutputFormat = (typeof VALID_FORMATS)[number];
12
+
9
13
  export interface FormatOptions {
10
14
  json?: boolean;
11
15
  withDescriptions?: boolean;
12
16
  verbose?: boolean;
13
17
  showSecrets?: boolean;
14
18
  logLevel?: string;
19
+ format?: OutputFormat;
15
20
  }
16
21
 
17
22
  export interface UnifiedItem {
@@ -345,9 +350,201 @@ function exampleValue(name: string, prop: Record<string, unknown>): unknown {
345
350
  }
346
351
  }
347
352
 
348
- /** Format a tool call result */
349
- export function formatCallResult(result: unknown, _options: FormatOptions): string {
350
- return JSON.stringify(parseNestedJson(result), null, 2);
353
+ /** Format a tool call result, dispatching on the --format option */
354
+ export function formatCallResult(result: unknown, options: FormatOptions): string {
355
+ const format = options.format ?? "json";
356
+
357
+ switch (format) {
358
+ case "text":
359
+ return formatCallResultAsText(result);
360
+ case "markdown":
361
+ return formatCallResultAsMarkdown(result);
362
+ case "json":
363
+ default:
364
+ return JSON.stringify(parseNestedJson(result), null, 2);
365
+ }
366
+ }
367
+
368
+ /** Extract human-readable text from an MCP tool call result */
369
+ function formatCallResultAsText(result: unknown): string {
370
+ const r = result as {
371
+ content?: Array<{
372
+ type: string;
373
+ text?: string;
374
+ data?: string;
375
+ mimeType?: string;
376
+ uri?: string;
377
+ }>;
378
+ isError?: boolean;
379
+ };
380
+
381
+ if (!r.content || !Array.isArray(r.content) || r.content.length === 0) {
382
+ return JSON.stringify(result, null, 2);
383
+ }
384
+
385
+ const parts: string[] = [];
386
+
387
+ for (const block of r.content) {
388
+ switch (block.type) {
389
+ case "text":
390
+ if (block.text !== undefined) {
391
+ try {
392
+ const parsed = JSON.parse(block.text);
393
+ parts.push(JSON.stringify(parsed, null, 2));
394
+ } catch {
395
+ parts.push(block.text);
396
+ }
397
+ }
398
+ break;
399
+ case "image":
400
+ parts.push(
401
+ `[image: ${block.mimeType ?? "unknown type"}, ${block.data ? Math.ceil((block.data.length * 3) / 4) : 0} bytes]`,
402
+ );
403
+ break;
404
+ case "resource":
405
+ parts.push(`[resource: ${block.uri ?? "unknown"}]`);
406
+ break;
407
+ default:
408
+ parts.push(`[${block.type}]`);
409
+ break;
410
+ }
411
+ }
412
+
413
+ let output = parts.join("\n");
414
+ if (r.isError) {
415
+ output = `error: ${output}`;
416
+ }
417
+ return output;
418
+ }
419
+
420
+ /** Render an MCP tool call result as styled markdown for terminal output */
421
+ function formatCallResultAsMarkdown(result: unknown): string {
422
+ const r = result as {
423
+ content?: Array<{
424
+ type: string;
425
+ text?: string;
426
+ data?: string;
427
+ mimeType?: string;
428
+ uri?: string;
429
+ }>;
430
+ isError?: boolean;
431
+ };
432
+
433
+ if (!r.content || !Array.isArray(r.content) || r.content.length === 0) {
434
+ return renderMarkdownToAnsi(jsonToMarkdown(result));
435
+ }
436
+
437
+ const parts: string[] = [];
438
+
439
+ for (const block of r.content) {
440
+ switch (block.type) {
441
+ case "text":
442
+ if (block.text !== undefined) {
443
+ try {
444
+ const parsed = JSON.parse(block.text);
445
+ parts.push(jsonToMarkdown(parsed));
446
+ } catch {
447
+ // Plain text / already markdown — pass through as-is
448
+ parts.push(block.text);
449
+ }
450
+ }
451
+ break;
452
+ case "image":
453
+ parts.push(
454
+ `[image: ${block.mimeType ?? "unknown type"}, ${block.data ? Math.ceil((block.data.length * 3) / 4) : 0} bytes]`,
455
+ );
456
+ break;
457
+ case "resource":
458
+ parts.push(`[resource: ${block.uri ?? "unknown"}]`);
459
+ break;
460
+ default:
461
+ parts.push(`[${block.type}]`);
462
+ break;
463
+ }
464
+ }
465
+
466
+ let output = parts.join("\n\n");
467
+ if (r.isError) {
468
+ output = `**error:** ${output}`;
469
+ }
470
+ return renderMarkdownToAnsi(output);
471
+ }
472
+
473
+ /** Convert a key name like "display_name" to "Display Name" */
474
+ function humanizeKey(key: string): string {
475
+ return key
476
+ .replace(/[_-]/g, " ")
477
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
478
+ .replace(/\b\w/g, (c) => c.toUpperCase());
479
+ }
480
+
481
+ /** Check if a value is a plain primitive (string, number, boolean, null) */
482
+ function isPrimitive(value: unknown): value is string | number | boolean | null {
483
+ return value === null || typeof value !== "object";
484
+ }
485
+
486
+ /**
487
+ * Convert a JSON value into a readable markdown document.
488
+ * Object keys become headings at their nesting depth (depth 1 = #, depth 2 = ##, etc.).
489
+ * Arrays of primitives become bullet lists. Arrays of objects get numbered sub-sections.
490
+ * Headings are capped at depth 6 (######); deeper nesting uses **bold** labels instead.
491
+ */
492
+ export function jsonToMarkdown(value: unknown, depth: number = 1): string {
493
+ if (isPrimitive(value)) {
494
+ return String(value ?? "null");
495
+ }
496
+
497
+ if (Array.isArray(value)) {
498
+ // Array of all primitives → bullet list
499
+ if (value.every(isPrimitive)) {
500
+ return value.map((v) => `- ${String(v ?? "null")}`).join("\n");
501
+ }
502
+ // Array of objects → numbered sub-sections
503
+ return value
504
+ .map((item, i) => {
505
+ if (isPrimitive(item)) {
506
+ return `- ${String(item ?? "null")}`;
507
+ }
508
+ const label = depth <= 6 ? `${"#".repeat(depth)} ${i + 1}` : `**${i + 1}**`;
509
+ return `${label}\n\n${jsonToMarkdown(item, depth + 1)}`;
510
+ })
511
+ .join("\n\n");
512
+ }
513
+
514
+ // Object → each key becomes a heading
515
+ const entries = Object.entries(value as Record<string, unknown>);
516
+ const lines: string[] = [];
517
+
518
+ for (const [key, val] of entries) {
519
+ const heading = humanizeKey(key);
520
+
521
+ if (isPrimitive(val)) {
522
+ if (depth <= 6) {
523
+ lines.push(`${"#".repeat(depth)} ${heading}\n\n${String(val ?? "null")}`);
524
+ } else {
525
+ lines.push(`**${heading}:** ${String(val ?? "null")}`);
526
+ }
527
+ } else if (Array.isArray(val) && val.every(isPrimitive)) {
528
+ // Array of primitives: heading then bullet list
529
+ const list = val.map((v) => `- ${String(v ?? "null")}`).join("\n");
530
+ if (depth <= 6) {
531
+ lines.push(`${"#".repeat(depth)} ${heading}\n\n${list}`);
532
+ } else {
533
+ lines.push(`**${heading}:**\n${list}`);
534
+ }
535
+ } else {
536
+ // Nested object or array of objects
537
+ const label = depth <= 6 ? `${"#".repeat(depth)} ${heading}` : `**${heading}**`;
538
+ lines.push(`${label}\n\n${jsonToMarkdown(val, depth + 1)}`);
539
+ }
540
+ }
541
+
542
+ return lines.join("\n\n");
543
+ }
544
+
545
+ /** Render a markdown string to ANSI-styled terminal output using Bun's built-in renderer */
546
+ export function renderMarkdownToAnsi(input: string): string {
547
+ return Bun.markdown.ansi(input);
351
548
  }
352
549
 
353
550
  /** Recursively parse JSON strings inside MCP content blocks */