High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(cli,mcp): expose page Markdown through pinchtab text --markdown and pinchtab_get_text mode (PIN-390)
Luigi Agosti8e1a1f69d6c8
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex c962e2ec..e7e92400 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -1,6 +1,7 @@package mainimport (+ "fmt""net""strings""time"@@ -173,9 +174,20 @@ func configureBrowserFlags() {textCmd.Flags().Bool("raw", false, "Raw extraction mode (alias of --full)")textCmd.Flags().Bool("full", false, "Return the full page text (document.body.innerText, the API's mode=full/mode=raw) instead of the default Readability-filtered content")+ textCmd.Flags().Bool("markdown", false, "Return the page as Markdown (preserves headings, links and tables); mutually exclusive with --full/--raw")+ textCmd.Flags().StringP("output", "o", "", "Write the extracted text to this file and print a one-line confirmation instead of the body")textCmd.Flags().String("frame", "", "Extract text from a specific iframe by frameId. If unset, uses the tab's active frame scope (set via `pinchtab frame`) or the top-level document.")textCmd.Flags().StringP("selector", "s", "", "Element selector to extract text from (ref/CSS/XPath/text)")textCmd.Flags().Bool("json", false, "Output full JSON response instead of just text content")+ textCmd.PreRunE = func(cmd *cobra.Command, args []string) error {+ markdown, _ := cmd.Flags().GetBool("markdown")+ raw, _ := cmd.Flags().GetBool("raw")+ full, _ := cmd.Flags().GetBool("full")+ if markdown && (raw || full) {+ return fmt.Errorf("--markdown cannot be combined with --full or --raw; each selects a different extraction mode")+ }+ return nil+ }titleCmd.Flags().String("frame", "", "Read title from a specific iframe by frameId. If unset, uses the tab's active frame scope or top-level document.")titleCmd.Flags().Bool("json", false, "Output full JSON response instead of just title")urlCmd.Flags().String("frame", "", "Read URL from a specific iframe by frameId. If unset, uses the tab's active frame scope or top-level document.")diff --git a/cmd/pinchtab/cmd_cli_register_test.go b/cmd/pinchtab/cmd_cli_register_test.goindex 72d7adb8..e0e1abc1 100644--- a/cmd/pinchtab/cmd_cli_register_test.go+++ b/cmd/pinchtab/cmd_cli_register_test.go@@ -1,6 +1,7 @@package mainimport (+ "strings""testing""github.com/spf13/cobra"@@ -32,6 +33,50 @@ func TestBrowserCommandRegistration(t *testing.T) {}}+func TestTextCommandRegistersMarkdownAndOutput(t *testing.T) {+ for _, name := range []string{"markdown", "output"} {+ if textCmd.Flags().Lookup(name) == nil {+ t.Errorf("textCmd missing flag %q", name)+ }+ }+ if f := textCmd.Flags().Lookup("output"); f != nil && f.Shorthand != "o" {+ t.Errorf("--output shorthand = %q, want o (the file-output idiom download/screenshot/capture use)", f.Shorthand)+ }+}++func TestTextMarkdownRefusesConflictingModesLocally(t *testing.T) {+ if textCmd.PreRunE == nil {+ t.Fatal("textCmd has no PreRunE, so --markdown --full costs a server round trip to discover")+ }+ defer func() {+ _ = textCmd.Flags().Set("markdown", "false")+ _ = textCmd.Flags().Set("full", "false")+ _ = textCmd.Flags().Set("raw", "false")+ }()++ for _, conflicting := range []string{"full", "raw"} {+ _ = textCmd.Flags().Set("markdown", "true")+ _ = textCmd.Flags().Set("full", "false")+ _ = textCmd.Flags().Set("raw", "false")+ if err := textCmd.Flags().Set(conflicting, "true"); err != nil {+ t.Fatal(err)+ }+ err := textCmd.PreRunE(textCmd, nil)+ if err == nil {+ t.Errorf("--markdown --%s was accepted; it must be refused with a usage error", conflicting)+ } else if !strings.Contains(err.Error(), "markdown") {+ t.Errorf("refusal = %v, want it to name --markdown", err)+ }+ }++ _ = textCmd.Flags().Set("full", "false")+ _ = textCmd.Flags().Set("raw", "false")+ _ = textCmd.Flags().Set("markdown", "true")+ if err := textCmd.PreRunE(textCmd, nil); err != nil {+ t.Errorf("--markdown alone was refused: %v", err)+ }+}+func TestCaptureCommandRegistersTabFlag(t *testing.T) {if captureCmd.Flags().Lookup("tab") == nil {t.Fatal("captureCmd missing --tab flag")diff --git a/docs/commands.md b/docs/commands.mdindex d8fe5f1c..d4960068 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -197,6 +197,8 @@ pinchtab snap --text # Text outputpinchtab text # Extract readable textpinchtab text --full # Full page innerTextpinchtab text --raw # Raw extraction+pinchtab text --markdown # Markdown (preserves links, tables)+pinchtab text --markdown --output page.md # Write Markdown to a file (one-line confirmation)pinchtab text --frame <frameId> # Read text from one iframepinchtab find <query> # Semantic element searchpinchtab find --threshold <0-1> # Minimum similarity scorediff --git a/docs/mcp.md b/docs/mcp.mdindex 174a18cf..b29b6858 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -139,7 +139,7 @@ PinchTab currently exposes 42 tools:- `pinchtab_frame`- `pinchtab_screenshot`- `pinchtab_capture` — paired screenshot + snapshot from one DOM epoch-- `pinchtab_get_text`+- `pinchtab_get_text` — extract page text; `mode` selects `readability` (default), `raw`, or `markdown` (preserves links and tables, best for article-shaped pages). `mode` supersedes the legacy boolean `raw`. Example: `pinchtab_get_text {"mode":"markdown"}`### Interactiondiff --git a/docs/reference/text.md b/docs/reference/text.mdindex 011dfb58..f9012b62 100644--- a/docs/reference/text.md+++ b/docs/reference/text.md@@ -48,7 +48,7 @@ text:| Field | Description ||-------|-------------|-| `extraction` | `readability`, `raw` (explicitly requested), or `readability_fallback` (Readability collapsed, raw text returned) |+| `extraction` | `readability`, `raw` (explicitly requested), `markdown` (page converted to Markdown), `markdown_fallback` (converter yielded nothing, raw text returned), or `readability_fallback` (Readability collapsed, raw text returned) || `textLength` | Length of the returned text || `rawLength` | Length of `document.body.innerText`, so coverage is computable |@@ -58,6 +58,13 @@ With `format=text` the body stays bare and the mode is reported in thefallback. The CLI prints a one-line note on stderr when a fallback fired; stdoutstays text-only.+`--markdown` (`mode=markdown`) converts the rendered page to Markdown, preserving+headings, inline links, and tables — the best mode for article-shaped pages you+want to keep or re-read. It is mutually exclusive with `--full`/`--raw`. Pair it+with `--output <file>` (`-o`) to write the Markdown to disk; the command then+prints only a one-line confirmation so a long page never floods an agent's+context.+## Examples```bash@@ -68,6 +75,10 @@ pinchtab textpinchtab text --fullpinchtab text --raw # Alias of --full+# Markdown (preserves headings, links, tables)+pinchtab text --markdown+pinchtab text --markdown --output page.md # writes the file, prints a one-line confirmation+# Extract text from specific elementpinchtab text "#main-content"pinchtab text --selector ".article-body"@@ -77,6 +88,7 @@ pinchtab text --frame FRAME123# API equivalentcurl "http://localhost:9867/text?mode=raw"+curl "http://localhost:9867/text?mode=markdown"curl "http://localhost:9867/text?selector=%23article-body"curl "http://localhost:9867/text?frameId=FRAME123&format=text"```@@ -89,6 +101,8 @@ curl "http://localhost:9867/text?frameId=FRAME123&format=text"| `--frame` | Extract from specific iframe by frameId || `--full` | Full page innerText instead of Readability || `--raw` | Alias for --full |+| `--markdown` | Convert the page to Markdown (headings, links, tables); mutually exclusive with `--full`/`--raw` |+| `--output`, `-o` | Write the extracted text to this file and print a one-line confirmation || `--json` | Output JSON instead of plain text || `--tab` | Target specific tab |@@ -99,7 +113,7 @@ curl "http://localhost:9867/text?frameId=FRAME123&format=text"| `selector` | Element selector for text extraction || `ref` | Snapshot ref (e.g., `e5`) || `frameId` | Target iframe ID |-| `mode` | `raw` for innerText, default for Readability |+| `mode` | `raw` for innerText, `markdown` for Markdown, default for Readability || `maxChars` | Truncate output || `format` | `text` for plain text response |diff --git a/internal/cli/actions/actions_text.go b/internal/cli/actions/actions_text.goindex 37523bb2..e6871377 100644--- a/internal/cli/actions/actions_text.go+++ b/internal/cli/actions/actions_text.go@@ -5,6 +5,7 @@ import ("net/http""net/url"+ "github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/cli/apiclient""github.com/pinchtab/pinchtab/internal/cli/output""github.com/pinchtab/pinchtab/internal/selector"@@ -20,7 +21,11 @@ func Text(client *http.Client, base, token string, cmd *cobra.Command, args []st// considers chrome are retained.raw, _ := cmd.Flags().GetBool("raw")full, _ := cmd.Flags().GetBool("full")- if raw || full {+ markdown, _ := cmd.Flags().GetBool("markdown")+ switch {+ case markdown:+ params.Set("mode", "markdown")+ case raw || full:params.Set("mode", "raw")params.Set("format", "text")}@@ -55,19 +60,38 @@ func Text(client *http.Client, base, token string, cmd *cobra.Command, args []streturn}+ outFile, _ := cmd.Flags().GetString("output")+body := apiclient.DoGetRaw(client, base, token, "/text", params)var result struct {Text string `json:"text"`Extraction string `json:"extraction"`}if err := json.Unmarshal(body, &result); err != nil {- output.Value(string(body))+ // A plain-text response (--full/--raw set format=text) is not an envelope;+ // the whole body is the content.+ writeTextOrPrint(outFile, string(body))return}if result.Extraction == extractionReadabilityFallback {output.Hint("readability extracted only a fragment of this page; returned the full page text instead (pass --full to request it directly)")}- output.Value(result.Text)+ writeTextOrPrint(outFile, result.Text)+}++// writeTextOrPrint writes the body to --output when set, printing a one-line+// confirmation so a long page never floods the agent's context, and otherwise+// prints the body. An explicit path is written as typed, overwrite included.+func writeTextOrPrint(outFile, text string) {+ if outFile == "" {+ output.Value(text)+ return+ }+ saved, err := writeOutputFile(outFile, false, []byte(text))+ if err != nil {+ cli.Fatal("Write failed: %v", err)+ }+ printSaved(saved, len(text))}// extractionReadabilityFallback mirrors the /text envelope value the serverdiff --git a/internal/cli/actions/actions_text_test.go b/internal/cli/actions/actions_text_test.goindex e8aa737a..0d5afb4f 100644--- a/internal/cli/actions/actions_text_test.go+++ b/internal/cli/actions/actions_text_test.go@@ -15,6 +15,8 @@ func newTextCmd() *cobra.Command {cmd := &cobra.Command{}cmd.Flags().Bool("raw", false, "")cmd.Flags().Bool("full", false, "")+ cmd.Flags().Bool("markdown", false, "")+ cmd.Flags().String("output", "", "")cmd.Flags().String("tab", "", "")cmd.Flags().String("frame", "", "")cmd.Flags().String("selector", "", "")@@ -67,6 +69,51 @@ func TestTextFull(t *testing.T) {}}+func TestTextMarkdown(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newTextCmd()+ _ = cmd.Flags().Set("markdown", "true")+ Text(client, m.base(), "", cmd, nil)+ if !strings.Contains(m.lastQuery, "mode=markdown") {+ t.Errorf("expected mode=markdown, got %s", m.lastQuery)+ }+ if strings.Contains(m.lastQuery, "format=text") {+ t.Errorf("markdown must not force format=text (the JSON envelope carries .text): %s", m.lastQuery)+ }+}++func TestTextMarkdownOutputWritesFileAndPrintsConfirmation(t *testing.T) {+ m := newMockServer()+ m.response = `{"url":"https://pinchtab.com","title":"Example","text":"# Title\n\nBody"}`+ defer m.close()++ out := t.TempDir() + "/page.md"+ cmd := newTextCmd()+ _ = cmd.Flags().Set("markdown", "true")+ _ = cmd.Flags().Set("output", out)++ stdout := captureStdout(t, func() {+ Text(m.server.Client(), m.base(), "", cmd, nil)+ })++ data, err := os.ReadFile(out)+ if err != nil {+ t.Fatalf("output file not written: %v", err)+ }+ if string(data) != "# Title\n\nBody" {+ t.Errorf("file body = %q, want the Markdown text", string(data))+ }+ if strings.Contains(stdout, "# Title") {+ t.Errorf("stdout carried the body instead of a one-line confirmation: %q", stdout)+ }+ if !strings.Contains(stdout, out) {+ t.Errorf("stdout = %q, want a one-line confirmation naming %s", stdout, out)+ }+}+func TestTextFrame(t *testing.T) {m := newMockServer()defer m.close()diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex 24ba3b04..8f860aa2 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -395,7 +395,11 @@ func handleGetText(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Cif tabID := optString(r, "tabId"); tabID != "" {q.Set("tabId", tabID)}- if v, ok := optBool(r, "raw"); ok && v {+ // mode supersedes the boolean raw so a caller can ask for markdown; raw:true+ // alone still maps to mode=raw for older callers.+ if mode := optString(r, "mode"); mode != "" {+ q.Set("mode", mode)+ } else if v, ok := optBool(r, "raw"); ok && v {q.Set("mode", "raw")}if format := optString(r, "format"); format != "" {diff --git a/internal/mcp/handlers_navigation_test.go b/internal/mcp/handlers_navigation_test.goindex 7e4655bb..96c5cd74 100644--- a/internal/mcp/handlers_navigation_test.go+++ b/internal/mcp/handlers_navigation_test.go@@ -370,6 +370,62 @@ func TestHandleGetText(t *testing.T) {}}+func TestHandleGetTextModeMarkdown(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_get_text", map[string]any{+ "mode": "markdown",+ }, srv)++ if got := getTextQueryValue(t, r, "mode"); got != "markdown" {+ t.Errorf("outbound query mode = %q, want markdown", got)+ }+}++func TestHandleGetTextRawMapsToModeRaw(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_get_text", map[string]any{+ "raw": true,+ }, srv)++ if got := getTextQueryValue(t, r, "mode"); got != "raw" {+ t.Errorf("outbound query mode = %q, want raw for raw:true", got)+ }+}++func TestHandleGetTextModeSupersedesRaw(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_get_text", map[string]any{+ "mode": "markdown",+ "raw": true,+ }, srv)++ if got := getTextQueryValue(t, r, "mode"); got != "markdown" {+ t.Errorf("outbound query mode = %q, want markdown; mode must win over raw when both are set", got)+ }+}++// getTextQueryValue reads the first value the mock recorded for a query key. The+// mock echoes r.URL.Query() (a map of string→[]string) into resp["query"].+func getTextQueryValue(t *testing.T, r *mcp.CallToolResult, key string) string {+ t.Helper()+ query, ok := resultJSON(t, r)["query"].(map[string]any)+ if !ok {+ t.Fatalf("result carried no query object: %s", resultText(t, r))+ }+ values, ok := query[key].([]any)+ if !ok || len(values) == 0 {+ return ""+ }+ s, _ := values[0].(string)+ return s+}+func TestHandleGetTextFormat(t *testing.T) {srv := mockPinchTab()defer srv.Close()diff --git a/internal/mcp/testdata/preamble_budget.json b/internal/mcp/testdata/preamble_budget.jsonindex 967183f7..43d9880f 100644--- a/internal/mcp/testdata/preamble_budget.json+++ b/internal/mcp/testdata/preamble_budget.json@@ -2,9 +2,9 @@{"surface": "mcp:allTools","minBytes": 18092,- "maxBytes": 40000,- "takenOn": "2026-09-11",- "commit": "1e7b8132"+ "maxBytes": 40500,+ "takenOn": "2026-09-12",+ "commit": "1ae3bf87"},{"surface": "skills/pinchtab-mcp/SKILL.md",diff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex 1b2f7b17..d5d0836f 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -93,6 +93,7 @@ func allTools() []mcp.Tool {mcp.NewTool("pinchtab_get_text",mcp.WithDescription("Extract readable text content from the current page. Inherits the current frame scope for the tab unless no frame is selected."),tabIDParam(),+ mcp.WithString("mode", mcp.Description("Extraction mode: 'readability' (default), 'raw', or 'markdown' (preserves links and tables; best for articles). Supersedes raw.")),mcp.WithBoolean("raw", mcp.Description("Return raw text without formatting")),mcp.WithString("format", mcp.Description("Response format: 'text'/'plain' for plain text, default JSON envelope")),mcp.WithNumber("maxChars", mcp.Description("Maximum characters in response (e.g. 3000)")),diff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex e6feb3e9..2dd05c01 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -221,8 +221,14 @@ Extract readable text from the page.pinchtab textpinchtab text --raw # no formatting cleanuppinchtab text "#main" # text from one element+pinchtab text --markdown # Markdown for article-shaped pages (keeps links, tables)+pinchtab text --markdown --output page.md # write Markdown to a file, print a one-line confirmation```+Prefer `--markdown` for articles, docs and other prose-heavy pages: it preserves+headings, inline links and tables, and `--output` keeps a long page out of the+context window. It cannot be combined with `--full`/`--raw`.+### `pinchtab find <query>`Find elements by text content or CSS selector.diff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.mdindex fb35acca..b7eb3575 100644--- a/skills/pinchtab/references/mcp.md+++ b/skills/pinchtab/references/mcp.md@@ -55,7 +55,7 @@ All tool names are prefixed with `pinchtab_`.| `pinchtab_snapshot` | Accessibility tree. Optional: `interactive`, `compact`, `format` (`compact` or `text`), `diff`, `selector`, `maxTokens`, `depth`, `noAnimations`, `tabId`. || `pinchtab_screenshot` | Capture screenshot. Optional: `format` (`jpeg` default, `png`), `quality`, `selector`, `scale`, `annotate`, `beyondViewport`, `browser`, `tabId`. Returns an MCP image content block (rendered inline by clients) plus a stable JSON text block `{"format", "annotations": [...]}`; `annotations` is `[]` by default and is populated with `{ref, role, name, tag, box {x,y,w,h}}` entries when `annotate=true` so refs in the picture map back to selectors. `beyondViewport=true` captures the full scrollable page (ignored when `selector` is set) and returns document-relative box coords. `browser` selects the browser (e.g. `chrome`, `cloak`). || `pinchtab_capture` | Paired screenshot + accessibility snapshot from the same DOM epoch. Optional: `selector`, `filter`, `format`, `quality`, `depth`, `wait` (`stable`/`load`/`none`), `withBounds`, `beyondViewport`, `requirePair`, `noAnimations`, `browser`, `tabId`. Returns an MCP image content block plus a JSON envelope with `epoch.domEpoch`, `pairing.navigated`, `image.coordinateSpace`, and per-node `boundingBox`. `browser` selects the browser (e.g. `chrome`, `cloak`); the static ghost-chrome runtime cannot paint, so it falls back to chrome. Use this instead of `pinchtab_screenshot` + `pinchtab_snapshot` when the model reads pixels AND acts on refs in the same turn. |-| `pinchtab_get_text` | Extract readable page text. Optional: `raw`, `format`, `maxChars`, `tabId`. |+| `pinchtab_get_text` | Extract page text. Optional: `mode` (`readability` default, `raw`, `markdown`), `raw`, `format`, `maxChars`, `tabId`. Use `mode:"markdown"` for article-shaped pages — it preserves links and tables; `mode` supersedes the boolean `raw`. Example: `pinchtab_get_text {"mode":"markdown"}`. |### Interaction| Tool | Description |diff --git a/tests/e2e/scenarios/cli/text-markdown-basic.sh b/tests/e2e/scenarios/cli/text-markdown-basic.shnew file mode 100755index 00000000..7735fc27--- /dev/null+++ b/tests/e2e/scenarios/cli/text-markdown-basic.sh@@ -0,0 +1,64 @@+#!/bin/bash+# text-markdown-basic.sh — CLI surface of mode=markdown: pinchtab text --markdown+# prints Markdown, --output writes a file with a one-line confirmation, and+# --markdown --full is refused locally with a usage error.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/cli.sh"++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab text --markdown prints Markdown structures"++pt_ok nav "${FIXTURES_URL}/markdown.html"+pt_ok text --markdown+assert_output_contains "# " "heading survives as Markdown"+assert_output_contains "## " "subheading survives as Markdown"+assert_output_contains "](https://example.com/link)" "inline link survives as Markdown"+assert_output_contains "- " "list item survives as Markdown"+assert_output_contains "|" "table survives as Markdown"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab text --markdown --output writes the file and prints one line"++OUT="/tmp/page-$$.md"+rm -f "$OUT"+pt_ok text --markdown --output "$OUT"++if [ -s "$OUT" ]; then+ pass_assert "markdown file written"+else+ fail_assert "markdown file not written to $OUT"+fi++if grep -q "# " "$OUT"; then+ pass_assert "written file carries Markdown"+else+ fail_assert "written file has no Markdown heading"+fi++# stdout is a single confirmation line, not the page body.+LINE_COUNT=$(printf '%s' "$PT_OUT" | grep -c '.')+if [ "$LINE_COUNT" -le 1 ]; then+ pass_assert "stdout is a single confirmation line"+else+ fail_assert "stdout had $LINE_COUNT lines, expected one confirmation line"+fi+assert_output_contains "$OUT" "confirmation names the file"+assert_output_not_contains "](https://example.com/link)" "body did not flood stdout"++rm -f "$OUT"+end_test++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab text --markdown --full is refused"++pt_fail text --markdown --full+if grep -qi "markdown" <<<"$PT_ERR"; then+ pass_assert "usage error names --markdown"+else+ fail_assert "usage error did not mention --markdown: $PT_ERR"+fi++end_testdiff --git a/tests/e2e/scenarios/manifest.json b/tests/e2e/scenarios/manifest.jsonindex 5aa8f3ca..a83308c5 100644--- a/tests/e2e/scenarios/manifest.json+++ b/tests/e2e/scenarios/manifest.json@@ -50,6 +50,13 @@"pr"]},+ "cli/text-markdown-basic.sh": {+ "tags": [+ "text",+ "markdown",+ "pr"+ ]+ },"api/browser-extended.sh": {"tags": ["browser",