@pokutuna/mcp-chrome-tabs 0.2.0 → 0.4.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 pokutuna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -7,7 +7,7 @@ Model Context Protocol (MCP) server that provides direct access to your browser'
7
7
  ## Key Features
8
8
 
9
9
  - **Direct browser tab access** - No web scraping needed, reads content from already open tabs
10
- - **Content optimized for AI** - Automatic readability processing and markdown conversion to reduce token usage
10
+ - **Content optimized for AI** - Automatic content extraction and markdown conversion to reduce token usage
11
11
  - **Active tab shortcut** - Instant access to currently focused tab without specifying IDs
12
12
  - **MCP listChanged notifications** - Follows MCP protocol to notify tab changes (support is limited in most clients)
13
13
 
@@ -53,6 +53,7 @@ The server accepts optional command line arguments for configuration:
53
53
  - `--application-name` - Application name to control (default: "Google Chrome")
54
54
  - `--exclude-hosts` - Comma-separated list of domains to exclude from tab listing and content access
55
55
  - `--check-interval` - Interval in milliseconds to check for tab changes and notify clients (default: 3000, set to 0 to disable)
56
+ - `--max-content-chars` - Truncates tab content to a maximum number of characters (default: 20000)
56
57
 
57
58
  #### Experimental Safari Support
58
59
 
@@ -1,7 +1,3 @@
1
- import { JSDOM } from "jsdom";
2
- import { Readability } from "@mozilla/readability";
3
- import TurndownService from "turndown";
4
- import turndownPluginGfm from "turndown-plugin-gfm";
5
1
  import { escapeAppleScript, executeAppleScript, separator, } from "./osascript.js";
6
2
  async function getChromeTabList(applicationName) {
7
3
  const sep = separator();
@@ -82,27 +78,19 @@ async function getPageContent(applicationName, tab) {
82
78
  return "ERROR" & "${sep}" & errMsg
83
79
  end try
84
80
  `;
85
- const result = await executeAppleScript(appleScript);
86
- if (result.startsWith(`ERROR${sep}`))
87
- throw new Error(result.split(sep)[1]);
88
- const parts = result.split(sep).map((part) => part.trim());
89
- if (parts.length < 3)
81
+ const scriptResult = await executeAppleScript(appleScript);
82
+ if (scriptResult.startsWith(`ERROR${sep}`)) {
83
+ throw new Error(scriptResult.split(sep)[1]);
84
+ }
85
+ const parts = scriptResult.split(sep).map((part) => part.trim());
86
+ if (parts.length < 3) {
90
87
  throw new Error("Failed to read the tab content");
88
+ }
91
89
  const [title, url, content] = parts;
92
- const dom = new JSDOM(content, { url });
93
- const reader = new Readability(dom.window.document, {
94
- charThreshold: 10,
95
- });
96
- const article = reader.parse();
97
- if (!article?.content)
98
- throw new Error("Failed to parse the page content");
99
- const turndownService = new TurndownService();
100
- turndownService.use(turndownPluginGfm.gfm);
101
- const md = turndownService.turndown(article.content);
102
90
  return {
103
91
  title,
104
92
  url,
105
- content: md,
93
+ content, // Return raw HTML content
106
94
  };
107
95
  }
108
96
  async function openURL(applicationName, url) {
@@ -2,6 +2,7 @@ import { execFile } from "child_process";
2
2
  import { promisify } from "util";
3
3
  const execFileAsync = promisify(execFile);
4
4
  export function escapeAppleScript(str) {
5
+ // https://discussions.apple.com/thread/4247426?sortBy=rank
5
6
  return str
6
7
  .replace(/\\/g, "\\\\")
7
8
  .replace(/"/g, '\\"')
@@ -9,7 +10,7 @@ export function escapeAppleScript(str) {
9
10
  .replace(/\r/g, "\\r");
10
11
  }
11
12
  export async function retry(fn, options) {
12
- const { maxRetries = 2, retryDelay = 1000 } = options || {};
13
+ const { maxRetries = 1, retryDelay = 1000 } = options || {};
13
14
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
14
15
  try {
15
16
  return await fn();
@@ -1,7 +1,3 @@
1
- import { JSDOM } from "jsdom";
2
- import { Readability } from "@mozilla/readability";
3
- import TurndownService from "turndown";
4
- import turndownPluginGfm from "turndown-plugin-gfm";
5
1
  import { escapeAppleScript, executeAppleScript, separator, } from "./osascript.js";
6
2
  async function getSafariTabList(applicationName) {
7
3
  const sep = separator();
@@ -82,27 +78,19 @@ async function getPageContent(applicationName, tab) {
82
78
  return "ERROR" & "${sep}" & errMsg
83
79
  end try
84
80
  `;
85
- const result = await executeAppleScript(appleScript);
86
- if (result.startsWith(`ERROR${sep}`))
87
- throw new Error(result.split(sep)[1]);
88
- const parts = result.split(sep).map((part) => part.trim());
89
- if (parts.length < 3)
81
+ const scriptResult = await executeAppleScript(appleScript);
82
+ if (scriptResult.startsWith(`ERROR${sep}`)) {
83
+ throw new Error(scriptResult.split(sep)[1]);
84
+ }
85
+ const parts = scriptResult.split(sep).map((part) => part.trim());
86
+ if (parts.length < 3) {
90
87
  throw new Error("Failed to read the tab content");
88
+ }
91
89
  const [title, url, content] = parts;
92
- const dom = new JSDOM(content, { url });
93
- const reader = new Readability(dom.window.document, {
94
- charThreshold: 10,
95
- });
96
- const article = reader.parse();
97
- if (!article?.content)
98
- throw new Error("Failed to parse the page content");
99
- const turndownService = new TurndownService();
100
- turndownService.use(turndownPluginGfm.gfm);
101
- const md = turndownService.turndown(article.content);
102
90
  return {
103
91
  title,
104
92
  url,
105
- content: md,
93
+ content, // Return raw HTML content
106
94
  };
107
95
  }
108
96
  async function openURL(applicationName, url) {
package/dist/cli.js CHANGED
@@ -26,6 +26,9 @@ OPTIONS:
26
26
  (default: "chrome")
27
27
  Options: "chrome", "safari"
28
28
 
29
+ --max-content-chars=<chars> Maximum content characters per single read
30
+ (default: 20000)
31
+
29
32
  --help Show this help message
30
33
 
31
34
 
@@ -67,6 +70,10 @@ function parseCliArgs(args) {
67
70
  type: "string",
68
71
  default: "",
69
72
  },
73
+ "max-content-chars": {
74
+ type: "string",
75
+ default: "20000",
76
+ },
70
77
  help: {
71
78
  type: "boolean",
72
79
  default: false,
@@ -82,6 +89,12 @@ function parseCliArgs(args) {
82
89
  return "safari";
83
90
  throw new Error(`Invalid --experimental-browser option: "${browser}". Use "chrome" or "safari".`);
84
91
  }
92
+ function parseIntWithDefault(value, defaultValue, minValue = 0) {
93
+ const parsed = parseInt(value, 10);
94
+ if (isNaN(parsed) || parsed < minValue)
95
+ return defaultValue;
96
+ return parsed;
97
+ }
85
98
  const parsed = {
86
99
  applicationName: values["application-name"],
87
100
  browser: parseBrowserOption(values["experimental-browser"]),
@@ -89,16 +102,27 @@ function parseCliArgs(args) {
89
102
  .split(",")
90
103
  .map((d) => d.trim())
91
104
  .filter(Boolean),
92
- checkInterval: parseInt(values["check-interval"], 10),
105
+ checkInterval: parseIntWithDefault(values["check-interval"], 3000, 0),
106
+ maxContentChars: parseIntWithDefault(values["max-content-chars"], 20000, 1),
93
107
  help: values.help,
94
108
  };
95
109
  return parsed;
96
110
  }
97
- const options = parseCliArgs(process.argv.slice(2));
98
- if (options.help) {
99
- showHelp();
100
- process.exit(0);
111
+ async function main() {
112
+ const options = parseCliArgs(process.argv.slice(2));
113
+ if (options.help) {
114
+ showHelp();
115
+ process.exit(0);
116
+ }
117
+ const server = await createMcpServer(options);
118
+ const transport = new StdioServerTransport();
119
+ await server.connect(transport);
120
+ const shutdown = async () => {
121
+ await transport.close();
122
+ await server.close();
123
+ process.exit(0);
124
+ };
125
+ process.on("SIGINT", shutdown);
126
+ process.on("SIGTERM", shutdown);
101
127
  }
102
- const server = await createMcpServer(options);
103
- const transport = new StdioServerTransport();
104
- await server.connect(transport);
128
+ await main().catch(console.error);
package/dist/mcp.d.ts CHANGED
@@ -5,5 +5,6 @@ export type McpServerOptions = {
5
5
  excludeHosts: string[];
6
6
  checkInterval: number;
7
7
  browser: Browser;
8
+ maxContentChars: number;
8
9
  };
9
10
  export declare function createMcpServer(options: McpServerOptions): Promise<McpServer>;
package/dist/mcp.js CHANGED
@@ -6,6 +6,8 @@ import { dirname, join } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import { createHash } from "crypto";
8
8
  import * as view from "./view.js";
9
+ import { Defuddle } from "defuddle/node";
10
+ import { withMockConsole } from "./util.js";
9
11
  function isExcludedHost(url, excludeHosts) {
10
12
  const u = new URL(url);
11
13
  return excludeHosts.some((d) => u.hostname === d || u.hostname.endsWith("." + d));
@@ -17,11 +19,21 @@ async function listTabs(opts) {
17
19
  }
18
20
  async function getTab(tabRef, opts) {
19
21
  const browser = getInterface(opts.browser);
20
- const content = await browser.getPageContent(opts.applicationName, tabRef);
21
- if (isExcludedHost(content.url, opts.excludeHosts)) {
22
+ const raw = await browser.getPageContent(opts.applicationName, tabRef);
23
+ if (isExcludedHost(raw.url, opts.excludeHosts)) {
22
24
  throw new Error("Content not available for excluded host");
23
25
  }
24
- return content;
26
+ const { result } = await withMockConsole(() => Defuddle(raw.content, raw.url, {
27
+ markdown: true,
28
+ }));
29
+ if (!result?.content) {
30
+ throw new Error("Failed to parse the page content");
31
+ }
32
+ return {
33
+ title: raw.title,
34
+ url: raw.url,
35
+ content: result.content,
36
+ };
25
37
  }
26
38
  async function packageVersion() {
27
39
  const packageJsonText = await readFile(join(dirname(fileURLToPath(import.meta.url)), "../package.json"), "utf8");
@@ -55,15 +67,22 @@ export async function createMcpServer(options) {
55
67
  debouncedNotificationMethods: ["notifications/resources/list_changed"],
56
68
  });
57
69
  server.registerTool("list_tabs", {
58
- description: "List all open tabs in the user's browser with their titles, URLs, and tab references",
59
- inputSchema: {},
60
- }, async () => {
70
+ description: "List all open tabs in the user's browser with their titles and tab references.",
71
+ inputSchema: {
72
+ includeUrl: z
73
+ .boolean()
74
+ .optional()
75
+ .default(false)
76
+ .describe("Include URLs in the output. Enable only when you need to reference specific URLs. (default: false, hostnames always included)"),
77
+ },
78
+ }, async (args) => {
79
+ const { includeUrl } = args;
61
80
  const tabs = await listTabs(options);
62
81
  return {
63
82
  content: [
64
83
  {
65
84
  type: "text",
66
- text: view.formatList(tabs),
85
+ text: view.formatList(tabs, includeUrl),
67
86
  },
68
87
  ],
69
88
  };
@@ -75,15 +94,22 @@ export async function createMcpServer(options) {
75
94
  .string()
76
95
  .optional()
77
96
  .describe("Tab reference from list_tabs output (e.g: ID:12345:67890). If omitted, uses the currently active tab."),
97
+ startIndex: z
98
+ .number()
99
+ .int()
100
+ .nonnegative()
101
+ .optional()
102
+ .default(0)
103
+ .describe("Starting character position for content extraction (default: 0)"),
78
104
  },
79
105
  }, async (args) => {
80
- const { id } = args;
106
+ const { id, startIndex } = args;
81
107
  const tab = await getTab(id ? view.parseTabRef(id) : null, options);
82
108
  return {
83
109
  content: [
84
110
  {
85
111
  type: "text",
86
- text: view.formatTabContent(tab),
112
+ text: view.formatTabContent(tab, startIndex, options.maxContentChars),
87
113
  },
88
114
  ],
89
115
  };
@@ -112,12 +138,13 @@ export async function createMcpServer(options) {
112
138
  mimeType: "text/markdown",
113
139
  }, async (uri) => {
114
140
  const tab = await getTab(null, options);
115
- const text = view.formatTabContent(tab);
141
+ // TODO: Add pagination support for resources (startIndex parameter)
142
+ const text = view.formatTabContent(tab, 0, undefined);
116
143
  return {
117
144
  contents: [
118
145
  {
119
146
  uri: uri.href,
120
- name: tab.title,
147
+ name: view.formatTabName(tab),
121
148
  text,
122
149
  mimeType: "text/markdown",
123
150
  size: new Blob([text]).size,
@@ -131,7 +158,7 @@ export async function createMcpServer(options) {
131
158
  return {
132
159
  resources: tabs.map((tab) => ({
133
160
  uri: view.formatUri(tab),
134
- name: tab.title,
161
+ name: view.formatTabName(tab),
135
162
  mimeType: "text/markdown",
136
163
  })),
137
164
  };
@@ -146,12 +173,13 @@ export async function createMcpServer(options) {
146
173
  tabId: String(tabId),
147
174
  };
148
175
  const tab = await getTab(tabRef, options);
149
- const text = view.formatTabContent(tab);
176
+ // TODO: Add pagination support for resources (startIndex parameter)
177
+ const text = view.formatTabContent(tab, 0, undefined);
150
178
  return {
151
179
  contents: [
152
180
  {
153
181
  uri: uri.href,
154
- name: tab.title,
182
+ name: view.formatTabName(tab),
155
183
  mimeType: "text/markdown",
156
184
  text,
157
185
  size: new Blob([text]).size,
package/dist/util.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export declare function withMockConsole<T>(fn: () => Promise<T>): Promise<{
2
+ result: T;
3
+ logs: unknown[][];
4
+ }>;
package/dist/util.js ADDED
@@ -0,0 +1,14 @@
1
+ export async function withMockConsole(fn) {
2
+ const originalConsoleLog = console.log;
3
+ const logs = [];
4
+ console.log = (...args) => {
5
+ logs.push(args);
6
+ };
7
+ try {
8
+ const result = await fn();
9
+ return { result, logs };
10
+ }
11
+ finally {
12
+ console.log = originalConsoleLog;
13
+ }
14
+ }
package/dist/view.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import type { Tab, TabRef, TabContent } from "./browser/browser.js";
2
2
  export declare function formatTabRef(tab: Tab): string;
3
3
  export declare function parseTabRef(tabRef: string): TabRef | null;
4
- export declare function formatList(tabs: Tab[]): string;
5
- export declare function formatListItem(tab: Tab): string;
6
- export declare function formatTabContent(tab: TabContent): string;
4
+ export declare function formatTabName(tab: {
5
+ title: string;
6
+ url: string;
7
+ }): string;
8
+ export declare function formatList(tabs: Tab[], includeUrl?: boolean): string;
9
+ export declare function formatListItem(tab: Tab, includeUrl?: boolean): string;
10
+ export declare function formatTabContent(tab: TabContent, startIndex?: number, maxContentChars?: number): string;
7
11
  export declare const uriTemplate = "tab://{windowId}/{tabId}";
8
12
  export declare function formatUri(ref: TabRef): string;
package/dist/view.js CHANGED
@@ -9,30 +9,54 @@ export function parseTabRef(tabRef) {
9
9
  const tabId = match[2];
10
10
  return { windowId, tabId };
11
11
  }
12
- function truncateUrl(tab, over = 120) {
13
- const url = tab.url;
14
- if (url.length <= over)
12
+ function getDomain(url) {
13
+ try {
14
+ const u = new URL(url);
15
+ return u.port ? `${u.hostname}:${u.port}` : u.hostname;
16
+ }
17
+ catch {
15
18
  return url;
16
- return url.slice(0, over) + "...";
19
+ }
17
20
  }
18
- export function formatList(tabs) {
19
- const list = tabs.map(formatListItem).join("\n");
21
+ export function formatTabName(tab) {
22
+ return `${tab.title} (${getDomain(tab.url)})`;
23
+ }
24
+ export function formatList(tabs, includeUrl = false) {
25
+ const list = tabs.map((tab) => formatListItem(tab, includeUrl)).join("\n");
20
26
  const header = `### Current Tabs (${tabs.length} tabs exists)\n`;
21
27
  return header + list;
22
28
  }
23
- export function formatListItem(tab) {
24
- return `- ${formatTabRef(tab)} [${tab.title}](${truncateUrl(tab)})`;
29
+ export function formatListItem(tab, includeUrl = false) {
30
+ if (includeUrl) {
31
+ return `- ${formatTabRef(tab)} [${tab.title}](${tab.url})`;
32
+ }
33
+ else {
34
+ return `- ${formatTabRef(tab)} ${formatTabName(tab)}`;
35
+ }
25
36
  }
26
- export function formatTabContent(tab) {
27
- return `
28
- ---
29
- title: ${tab.title}
30
- ---
31
- ${tab.content}
32
- `.trimStart();
37
+ export function formatTabContent(tab, startIndex = 0, maxContentChars) {
38
+ const frontMatters = [
39
+ { key: "url", value: tab.url },
40
+ { key: "title", value: tab.title },
41
+ ];
42
+ let content = tab.content;
43
+ if (startIndex > 0) {
44
+ content = content.slice(startIndex);
45
+ frontMatters.push({ key: "startIndex", value: startIndex });
46
+ }
47
+ const truncation = maxContentChars !== undefined && content.length > maxContentChars;
48
+ if (truncation) {
49
+ content = content.slice(0, maxContentChars);
50
+ const nextStart = startIndex + maxContentChars;
51
+ content += `\n\n<ERROR>Content truncated. Read with startIndex of ${nextStart} to get more content.</ERROR>`;
52
+ frontMatters.push({ key: "truncated", value: truncation });
53
+ }
54
+ const frontMatterText = frontMatters
55
+ .map(({ key, value }) => `${key}: ${value}`)
56
+ .join("\n");
57
+ return ["---", frontMatterText, "---", content].join("\n");
33
58
  }
34
59
  export const uriTemplate = "tab://{windowId}/{tabId}";
35
60
  export function formatUri(ref) {
36
- // TODO give domain & title for incremental search
37
61
  return `tab://${ref.windowId}/${ref.tabId}`;
38
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pokutuna/mcp-chrome-tabs",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/pokutuna/mcp-chrome-tabs"
@@ -23,21 +23,20 @@
23
23
  "lint:fix": "prettier --write .",
24
24
  "prepublishOnly": "npm run build",
25
25
  "start": "node dist/index.js",
26
- "test": "vitest",
27
- "test:run": "vitest run"
26
+ "test": "vitest run",
27
+ "test:watch": "vitest",
28
+ "test:e2e": "playwright test"
28
29
  },
29
30
  "dependencies": {
30
31
  "@modelcontextprotocol/sdk": "^1.16.0",
31
- "@mozilla/readability": "^0.6.0",
32
- "jsdom": "^26.1.0",
33
- "turndown": "^7.2.0",
34
- "turndown-plugin-gfm": "^1.0.2",
32
+ "defuddle": "^0.6.4",
33
+ "jsdom": "^24.0.0",
35
34
  "zod": "^3.25.76"
36
35
  },
37
36
  "devDependencies": {
38
- "@types/jsdom": "^21.1.7",
37
+ "@playwright/test": "^1.54.1",
39
38
  "@types/node": "^20.11.17",
40
- "@types/turndown": "^5.0.5",
39
+ "playwright": "^1.54.1",
41
40
  "prettier": "^3.6.2",
42
41
  "tsx": "^4.7.1",
43
42
  "typescript": "~5.8.3",