taskwindow 0.1.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/package.json +36 -0
- package/src/bridge.js +135 -0
- package/src/config.js +44 -0
- package/src/index.js +152 -0
- package/src/mcp-http.js +27 -0
- package/src/tools.js +319 -0
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "taskwindow",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TaskWindow local daemon: bridges the TaskWindow Chrome extension to any MCP client over Streamable HTTP",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"taskwindow": "src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"start": "node src/index.js",
|
|
12
|
+
"test": "node test/run.mjs"
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=18"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
19
|
+
"ws": "^8.18.0",
|
|
20
|
+
"zod": "^3.24.0"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"src"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/clawnify/TaskWindow.git"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"mcp",
|
|
31
|
+
"chrome",
|
|
32
|
+
"browser-automation",
|
|
33
|
+
"coding-agent"
|
|
34
|
+
],
|
|
35
|
+
"license": "MIT"
|
|
36
|
+
}
|
package/src/bridge.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { WebSocketServer } from "ws";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
const PROTOCOL_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Bridges MCP tool calls to the TaskWindow Chrome extension over WebSocket.
|
|
8
|
+
*
|
|
9
|
+
* The extension dials in as a WS client (ws://127.0.0.1:<port>/ws?token=...);
|
|
10
|
+
* tool calls go out as {type:"tool_call", id, tool, params} and come back as
|
|
11
|
+
* {type:"tool_result", id, ok, ...}. Token is checked at handshake time.
|
|
12
|
+
*/
|
|
13
|
+
export class Bridge {
|
|
14
|
+
constructor({ token, logger = console }) {
|
|
15
|
+
this.token = token;
|
|
16
|
+
this.logger = logger;
|
|
17
|
+
this.ext = null; // active extension WebSocket
|
|
18
|
+
this.pending = new Map(); // tool_call id -> {resolve, reject, timer}
|
|
19
|
+
this.lastHello = null;
|
|
20
|
+
this.wss = null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
start(httpServer) {
|
|
24
|
+
this.wss = new WebSocketServer({ server: httpServer, path: "/ws" });
|
|
25
|
+
|
|
26
|
+
this.wss.on("connection", (ws, req) => {
|
|
27
|
+
const url = new URL(req.url, "http://localhost");
|
|
28
|
+
const token = url.searchParams.get("token");
|
|
29
|
+
if (token !== this.token) {
|
|
30
|
+
ws.close(4401, "invalid or missing token");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Single active extension connection: newest wins.
|
|
35
|
+
if (this.ext && this.ext !== ws) {
|
|
36
|
+
this.logger.log("[bridge] replacing existing extension connection");
|
|
37
|
+
try {
|
|
38
|
+
this.ext.close(4000, "superseded by a new extension connection");
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
this.ext = ws;
|
|
42
|
+
|
|
43
|
+
ws.on("message", (raw) => this.#onMessage(ws, raw));
|
|
44
|
+
ws.on("close", () => {
|
|
45
|
+
if (this.ext === ws) {
|
|
46
|
+
this.ext = null;
|
|
47
|
+
this.lastHello = null;
|
|
48
|
+
this.logger.log("[bridge] extension disconnected");
|
|
49
|
+
}
|
|
50
|
+
this.#failAllPending(new Error("TaskWindow extension disconnected"));
|
|
51
|
+
});
|
|
52
|
+
ws.on("error", () => {});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Ping to keep the MV3 service worker alive and detect dead peers.
|
|
56
|
+
this.pingTimer = setInterval(() => {
|
|
57
|
+
if (this.ext && this.ext.readyState === 0 /* CONNECTING */) return;
|
|
58
|
+
for (const client of this.wss.clients) {
|
|
59
|
+
if (client.readyState === 1 /* OPEN */) client.ping();
|
|
60
|
+
}
|
|
61
|
+
}, 25_000);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
stop() {
|
|
65
|
+
clearInterval(this.pingTimer);
|
|
66
|
+
this.#failAllPending(new Error("daemon shutting down"));
|
|
67
|
+
if (this.ext) try { this.ext.close(); } catch {}
|
|
68
|
+
if (this.wss) try { this.wss.close(); } catch {}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
get connected() {
|
|
72
|
+
return !!this.ext && this.ext.readyState === 1 /* OPEN */;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Send a tool call to the extension and await its result.
|
|
77
|
+
* Returns the extension's result object ({text?, image?, data?}).
|
|
78
|
+
*/
|
|
79
|
+
sendTool(tool, params, timeoutMs = 30_000) {
|
|
80
|
+
if (!this.connected) {
|
|
81
|
+
return Promise.reject(
|
|
82
|
+
new Error(
|
|
83
|
+
"TaskWindow extension is not connected. Open Chrome with the extension enabled (check its options page shows Connected)."
|
|
84
|
+
)
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
const id = randomUUID();
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
const timer = setTimeout(() => {
|
|
90
|
+
this.pending.delete(id);
|
|
91
|
+
reject(new Error(`TaskWindow extension did not answer "${tool}" within ${Math.round(timeoutMs / 1000)}s`));
|
|
92
|
+
}, timeoutMs);
|
|
93
|
+
this.pending.set(id, { resolve, reject, timer, tool });
|
|
94
|
+
this.ext.send(JSON.stringify({ type: "tool_call", id, tool, params }));
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
#onMessage(ws, raw) {
|
|
99
|
+
let msg;
|
|
100
|
+
try {
|
|
101
|
+
msg = JSON.parse(raw.toString());
|
|
102
|
+
} catch {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
switch (msg.type) {
|
|
106
|
+
case "hello":
|
|
107
|
+
this.lastHello = msg;
|
|
108
|
+
this.logger.log(`[bridge] extension connected (protocol ${msg.protocol}, ${msg.version || "?"}, ${msg.userAgent || "unknown chrome"})`);
|
|
109
|
+
break;
|
|
110
|
+
case "pong":
|
|
111
|
+
break;
|
|
112
|
+
case "tool_result": {
|
|
113
|
+
const entry = this.pending.get(msg.id);
|
|
114
|
+
if (!entry) return;
|
|
115
|
+
clearTimeout(entry.timer);
|
|
116
|
+
this.pending.delete(msg.id);
|
|
117
|
+
if (msg.ok) entry.resolve(msg.result ?? {});
|
|
118
|
+
else entry.reject(new Error(msg.error || `extension tool "${entry.tool}" failed`));
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
default:
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
#failAllPending(err) {
|
|
127
|
+
for (const [, entry] of this.pending) {
|
|
128
|
+
clearTimeout(entry.timer);
|
|
129
|
+
entry.reject(err);
|
|
130
|
+
}
|
|
131
|
+
this.pending.clear();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export { PROTOCOL_VERSION };
|
package/src/config.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
|
|
6
|
+
export function loadConfig() {
|
|
7
|
+
const port = Number(process.env.TASKWINDOW_PORT || process.env.AGENTTAB_PORT || 9377);
|
|
8
|
+
const dir = process.env.TASKWINDOW_DIR || process.env.OPENTAB_DIR || process.env.AGENTTAB_DIR || join(homedir(), ".taskwindow");
|
|
9
|
+
let token = process.env.TASKWINDOW_TOKEN || process.env.OPENTAB_TOKEN || process.env.AGENTTAB_TOKEN;
|
|
10
|
+
|
|
11
|
+
if (!token) {
|
|
12
|
+
const tokenPath = join(dir, "token");
|
|
13
|
+
try {
|
|
14
|
+
token = readFileSync(tokenPath, "utf8").trim();
|
|
15
|
+
} catch {
|
|
16
|
+
mkdirSync(dir, { recursive: true });
|
|
17
|
+
// One-time migration from pre-rename config dirs.
|
|
18
|
+
const legacyPaths = [join(homedir(), ".opentab", "token"), join(homedir(), ".agenttab", "token")];
|
|
19
|
+
let migrated = null;
|
|
20
|
+
for (const legacyPath of legacyPaths || []) {
|
|
21
|
+
try {
|
|
22
|
+
token = readFileSync(legacyPath, "utf8").trim();
|
|
23
|
+
migrated = legacyPath;
|
|
24
|
+
break;
|
|
25
|
+
} catch {}
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
if (migrated) {
|
|
29
|
+
writeFileSync(tokenPath, token + "\n", { mode: 0o600 });
|
|
30
|
+
console.log(`[taskwindow] migrated token from ${migrated} to ${tokenPath}`);
|
|
31
|
+
} else {
|
|
32
|
+
token = randomBytes(24).toString("base64url");
|
|
33
|
+
writeFileSync(tokenPath, token + "\n", { mode: 0o600 });
|
|
34
|
+
console.log(`[taskwindow] generated new token at ${tokenPath}`);
|
|
35
|
+
}
|
|
36
|
+
} catch (err) {
|
|
37
|
+
console.error(`[taskwindow] token bootstrap failed:`, err.message);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return { port, dir, token };
|
|
44
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { loadConfig } from "./config.js";
|
|
5
|
+
import { Bridge } from "./bridge.js";
|
|
6
|
+
import { createMcpRequestHandler } from "./mcp-http.js";
|
|
7
|
+
|
|
8
|
+
const config = loadConfig();
|
|
9
|
+
const bridge = new Bridge({ token: config.token });
|
|
10
|
+
const handleMcp = createMcpRequestHandler({ bridge });
|
|
11
|
+
|
|
12
|
+
// One-time pairing: the daemon prints a short code at startup; the extension
|
|
13
|
+
// exchanges it for the real token via POST /pair (loopback-only). This defends
|
|
14
|
+
// the pairing endpoint against other local user accounts; a same-user process
|
|
15
|
+
// could read the token file directly, so the code adds no obstacle there.
|
|
16
|
+
const PAIR_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // no 0/O/1/I
|
|
17
|
+
const pairCode = Array.from(randomBytes(6))
|
|
18
|
+
.map((b) => PAIR_ALPHABET[b % PAIR_ALPHABET.length])
|
|
19
|
+
.join("");
|
|
20
|
+
const pairFailures = []; // timestamps of failed attempts, rolling window
|
|
21
|
+
const PAIR_WINDOW_MS = 60_000;
|
|
22
|
+
const PAIR_MAX_FAILURES = 5;
|
|
23
|
+
|
|
24
|
+
function pairRateLimited() {
|
|
25
|
+
const cutoff = Date.now() - PAIR_WINDOW_MS;
|
|
26
|
+
while (pairFailures.length > 0 && pairFailures[0] < cutoff) pairFailures.shift();
|
|
27
|
+
return pairFailures.length >= PAIR_MAX_FAILURES;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const BODY_LIMIT = 50 * 1024 * 1024; // file_upload transfers bytes through the daemon
|
|
31
|
+
|
|
32
|
+
function sendJson(res, code, obj) {
|
|
33
|
+
const body = JSON.stringify(obj);
|
|
34
|
+
res.writeHead(code, {
|
|
35
|
+
"content-type": "application/json",
|
|
36
|
+
"content-length": Buffer.byteLength(body),
|
|
37
|
+
});
|
|
38
|
+
res.end(body);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function readBody(req) {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const chunks = [];
|
|
44
|
+
let size = 0;
|
|
45
|
+
req.on("data", (c) => {
|
|
46
|
+
size += c.length;
|
|
47
|
+
if (size > BODY_LIMIT) {
|
|
48
|
+
reject(new Error("body too large"));
|
|
49
|
+
req.destroy();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
chunks.push(c);
|
|
53
|
+
});
|
|
54
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
55
|
+
req.on("error", reject);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const server = http.createServer(async (req, res) => {
|
|
60
|
+
const url = new URL(req.url, `http://127.0.0.1:${config.port}`);
|
|
61
|
+
|
|
62
|
+
if (url.pathname === "/health") {
|
|
63
|
+
sendJson(res, 200, {
|
|
64
|
+
ok: true,
|
|
65
|
+
version: "0.1.0",
|
|
66
|
+
extensionConnected: bridge.connected,
|
|
67
|
+
port: config.port,
|
|
68
|
+
});
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (url.pathname === "/pair") {
|
|
73
|
+
if (pairRateLimited()) {
|
|
74
|
+
sendJson(res, 429, { error: "too many failed pairing attempts; wait a minute" });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
let body;
|
|
78
|
+
try {
|
|
79
|
+
body = JSON.parse((await readBody(req)).toString("utf8"));
|
|
80
|
+
} catch {
|
|
81
|
+
sendJson(res, 400, { error: "invalid JSON body" });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const code = String(body?.code || "").trim().toUpperCase();
|
|
85
|
+
if (code !== pairCode) {
|
|
86
|
+
pairFailures.push(Date.now());
|
|
87
|
+
sendJson(res, 403, { error: "invalid pairing code" });
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
sendJson(res, 200, { token: config.token });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (url.pathname === "/mcp") {
|
|
95
|
+
const auth = req.headers.authorization || "";
|
|
96
|
+
if (auth !== `Bearer ${config.token}`) {
|
|
97
|
+
sendJson(res, 401, { error: "invalid or missing bearer token" });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (req.method !== "POST") {
|
|
102
|
+
// Stateless mode: no SSE streams, no sessions to terminate.
|
|
103
|
+
res.setHeader("allow", "POST");
|
|
104
|
+
sendJson(res, 405, { error: "method not allowed; POST JSON-RPC to /mcp" });
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
try {
|
|
109
|
+
const raw = await readBody(req);
|
|
110
|
+
let body;
|
|
111
|
+
try {
|
|
112
|
+
body = JSON.parse(raw.toString("utf8"));
|
|
113
|
+
} catch {
|
|
114
|
+
sendJson(res, 400, { error: "invalid JSON body" });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
await handleMcp(req, res, body);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
if (!res.headersSent) sendJson(res, 500, { error: err.message });
|
|
120
|
+
else res.end();
|
|
121
|
+
}
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
sendJson(res, 404, { error: "not found" });
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
bridge.start(server);
|
|
129
|
+
|
|
130
|
+
server.on("error", (err) => {
|
|
131
|
+
if (err.code === "EADDRINUSE") {
|
|
132
|
+
console.error(`[taskwindow] port ${config.port} is already in use — is another daemon running? (TASKWINDOW_PORT to change)`);
|
|
133
|
+
process.exit(1);
|
|
134
|
+
}
|
|
135
|
+
console.error(`[taskwindow] server error:`, err);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
server.listen(config.port, "127.0.0.1", () => {
|
|
139
|
+
console.log(`[taskwindow] daemon listening on http://127.0.0.1:${config.port}`);
|
|
140
|
+
console.log(`[taskwindow] MCP endpoint: http://127.0.0.1:${config.port}/mcp`);
|
|
141
|
+
console.log(`[taskwindow] pairing code: ${pairCode} — enter it in the TaskWindow extension options to connect (valid while this daemon runs)`);
|
|
142
|
+
console.log(`[taskwindow] waiting for the TaskWindow extension to connect on ws://127.0.0.1:${config.port}/ws`);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
for (const sig of ["SIGINT", "SIGTERM"]) {
|
|
146
|
+
process.on(sig, () => {
|
|
147
|
+
console.log(`\n[taskwindow] ${sig} received, shutting down`);
|
|
148
|
+
bridge.stop();
|
|
149
|
+
server.close(() => process.exit(0));
|
|
150
|
+
setTimeout(() => process.exit(0), 1500).unref();
|
|
151
|
+
});
|
|
152
|
+
}
|
package/src/mcp-http.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
3
|
+
import { registerTools } from "./tools.js";
|
|
4
|
+
|
|
5
|
+
const SERVER_INFO = { name: "taskwindow", version: "0.1.0" };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Stateless Streamable-HTTP MCP endpoint: every POST /mcp request gets a fresh
|
|
9
|
+
* server+transport pair. No session state — any MCP client that speaks
|
|
10
|
+
* Streamable HTTP can hit it.
|
|
11
|
+
*/
|
|
12
|
+
export function createMcpRequestHandler({ bridge, logger = console }) {
|
|
13
|
+
return async function handleMcpRequest(req, res, parsedBody) {
|
|
14
|
+
const server = new McpServer(SERVER_INFO);
|
|
15
|
+
registerTools(server, { bridge, logger });
|
|
16
|
+
const transport = new StreamableHTTPServerTransport({
|
|
17
|
+
sessionIdGenerator: undefined,
|
|
18
|
+
enableJsonResponse: true,
|
|
19
|
+
});
|
|
20
|
+
res.on("close", () => {
|
|
21
|
+
transport.close().catch(() => {});
|
|
22
|
+
server.close().catch(() => {});
|
|
23
|
+
});
|
|
24
|
+
await server.connect(transport);
|
|
25
|
+
await transport.handleRequest(req, res, parsedBody);
|
|
26
|
+
};
|
|
27
|
+
}
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
const tabId = z.number().int().describe("Tab ID from tabs_list. Defaults to the active tab in the current task's tab group.");
|
|
4
|
+
|
|
5
|
+
// Result contract with the extension: {text?, image?: {data, mimeType}, data?}.
|
|
6
|
+
// The MCP layer turns `image` into an image content block and everything else
|
|
7
|
+
// into text blocks.
|
|
8
|
+
|
|
9
|
+
const toolDefs = [
|
|
10
|
+
{
|
|
11
|
+
name: "tabs_list",
|
|
12
|
+
description:
|
|
13
|
+
"List the tabs the agent may use (id, title, URL, active state) — by default only the tabs it created, grouped by task. Always call this first to discover tab IDs.",
|
|
14
|
+
inputSchema: {},
|
|
15
|
+
timeoutMs: 10_000,
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
name: "tabs_create",
|
|
19
|
+
description:
|
|
20
|
+
"Open a new tab. Tabs live in a tab group named after the task they belong to (in the agent's own window); " +
|
|
21
|
+
"creating a tab for an existing task name reuses that group instead of duplicating it.",
|
|
22
|
+
inputSchema: {
|
|
23
|
+
url: z.string().url().describe("URL to open (include the scheme, e.g. https://...)"),
|
|
24
|
+
active: z.boolean().optional().describe("Bring the new tab to the front (default true)"),
|
|
25
|
+
task: z.string().optional().describe("Task name for the tab group, e.g. \"Research competitors\". Reuses an existing group with the same name; defaults to the current task."),
|
|
26
|
+
},
|
|
27
|
+
timeoutMs: 15_000,
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: "tabs_close",
|
|
31
|
+
description: "Close a tab.",
|
|
32
|
+
inputSchema: { tabId },
|
|
33
|
+
timeoutMs: 10_000,
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: "navigate",
|
|
37
|
+
description:
|
|
38
|
+
"Navigate a tab to a URL. Waits (up to 10s) for the load event, then returns the tab's URL and title.",
|
|
39
|
+
inputSchema: { url: z.string().url(), tabId: tabId.optional() },
|
|
40
|
+
timeoutMs: 30_000,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "computer",
|
|
44
|
+
description:
|
|
45
|
+
"Screenshot and low-level mouse/keyboard control of a tab via the Chrome DevTools Protocol. " +
|
|
46
|
+
"Actions: screenshot (PNG of the viewport, or full page with fullPage), left_click / right_click / " +
|
|
47
|
+
"middle_click / double_click / triple_click (at x,y), type (text into the focused element), " +
|
|
48
|
+
"key (named key press, e.g. Enter, Tab, Escape, ArrowLeft, Backspace), scroll (by dx/dy pixels), " +
|
|
49
|
+
"mouse_move, wait. Coordinates come from the last screenshot. NOTE: while attached, Chrome shows a " +
|
|
50
|
+
'"TaskWindow started debugging this browser" infobar — this is unavoidable with CDP-based control.',
|
|
51
|
+
inputSchema: {
|
|
52
|
+
action: z.enum([
|
|
53
|
+
"screenshot", "left_click", "right_click", "middle_click", "double_click", "triple_click",
|
|
54
|
+
"type", "key", "scroll", "mouse_move", "wait",
|
|
55
|
+
]),
|
|
56
|
+
tabId: tabId.optional(),
|
|
57
|
+
x: z.number().int().optional().describe("X coordinate in viewport pixels (clicks, scroll origin, mouse_move)"),
|
|
58
|
+
y: z.number().int().optional().describe("Y coordinate in viewport pixels"),
|
|
59
|
+
text: z.string().optional().describe('Text for the "type" action'),
|
|
60
|
+
key: z.string().optional().describe('Key name for the "key" action, e.g. "Enter", "a", "ArrowDown"'),
|
|
61
|
+
dx: z.number().int().optional().describe("Horizontal scroll delta in pixels"),
|
|
62
|
+
dy: z.number().int().optional().describe("Vertical scroll delta in pixels (positive scrolls down)"),
|
|
63
|
+
ms: z.number().int().min(0).max(10_000).optional().describe('Milliseconds for the "wait" action (max 10000)'),
|
|
64
|
+
fullPage: z.boolean().optional().describe('For "screenshot": capture the whole scrollable page instead of the viewport'),
|
|
65
|
+
},
|
|
66
|
+
timeoutMs: 30_000,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: "set_viewport",
|
|
70
|
+
description:
|
|
71
|
+
"Open a responsive view: a dedicated harness window in the current task's tab group rendering the current page in one fixed-size iframe per viewport (media queries, vw/vh and touch resolve exactly per frame; several breakpoints side by side). " +
|
|
72
|
+
"Sites that refuse framing automatically fall back to a dedicated emulated window per viewport. Only these windows are affected — other windows and tab groups are untouched. " +
|
|
73
|
+
"Each result reports the page's own innerWidth (trust it over screenshots). Typical flow: set_viewport, computer screenshot / read_page on the returned tabIds, then set_viewport with no arguments to close. " +
|
|
74
|
+
"Note: frames may render logged out on cookie-partitioned sites — the emulated-window fallback has full cookies.",
|
|
75
|
+
inputSchema: {
|
|
76
|
+
viewports: z.array(z.object({
|
|
77
|
+
width: z.number().int().min(200).max(4000),
|
|
78
|
+
height: z.number().int().min(200).max(4000),
|
|
79
|
+
})).min(1).max(4).optional().describe("Sizes to render side by side, e.g. [{\"width\":390,\"height\":844},{\"width\":1280,\"height\":800}]. Omit to close the responsive view."),
|
|
80
|
+
url: z.string().url().optional().describe("Page to render (defaults to the current tab's URL)"),
|
|
81
|
+
tabId: tabId.optional(),
|
|
82
|
+
},
|
|
83
|
+
timeoutMs: 30_000,
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
name: "read_page",
|
|
87
|
+
description:
|
|
88
|
+
"Structured accessibility-style snapshot of the page: a text tree of interactive elements and content, " +
|
|
89
|
+
"each labelled with a ref (e.g. e42) you can pass to form_input / file_upload. Cheaper and more reliable " +
|
|
90
|
+
"than a screenshot for forms and navigation.",
|
|
91
|
+
inputSchema: { tabId: tabId.optional() },
|
|
92
|
+
timeoutMs: 20_000,
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
name: "find",
|
|
96
|
+
description:
|
|
97
|
+
"Find elements on the page matching a query (matches role, accessible name and visible text, case-insensitive). " +
|
|
98
|
+
"Returns matching refs plus enough context to pick between them.",
|
|
99
|
+
inputSchema: { query: z.string().min(1), tabId: tabId.optional() },
|
|
100
|
+
timeoutMs: 20_000,
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
name: "get_page_text",
|
|
104
|
+
description: "Extract the page's visible text content (like copy-pasting the page body).",
|
|
105
|
+
inputSchema: {
|
|
106
|
+
tabId: tabId.optional(),
|
|
107
|
+
maxLength: z.number().int().min(100).max(500_000).optional().describe("Truncate output to this many characters (default 50000)"),
|
|
108
|
+
},
|
|
109
|
+
timeoutMs: 20_000,
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
name: "form_input",
|
|
113
|
+
description:
|
|
114
|
+
"Fill a form field: text inputs, textareas, checkboxes, radios, <select>s and contenteditable elements. " +
|
|
115
|
+
"Targets the element by ref (from read_page/find) or a CSS selector.",
|
|
116
|
+
inputSchema: {
|
|
117
|
+
value: z.union([z.string(), z.number(), z.boolean()]).describe("Value to set. For checkboxes/radios use true/false; for selects use the option value or visible text."),
|
|
118
|
+
ref: z.string().optional().describe("Element ref from read_page/find (e.g. e42)"),
|
|
119
|
+
selector: z.string().optional().describe("CSS selector as fallback when no ref is available"),
|
|
120
|
+
clear: z.boolean().optional().describe("Clear the field before typing (default true for text fields)"),
|
|
121
|
+
tabId: tabId.optional(),
|
|
122
|
+
},
|
|
123
|
+
timeoutMs: 20_000,
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
name: "file_upload",
|
|
127
|
+
description:
|
|
128
|
+
"Attach local file content to a file input (<input type=file>). The file bytes are transferred through the " +
|
|
129
|
+
"daemon; target the input by ref or CSS selector.",
|
|
130
|
+
inputSchema: {
|
|
131
|
+
files: z.array(z.object({
|
|
132
|
+
name: z.string().describe("File name (shown to the site)"),
|
|
133
|
+
mimeType: z.string().optional().describe("MIME type, e.g. application/pdf"),
|
|
134
|
+
data: z.string().describe("File content, base64-encoded"),
|
|
135
|
+
})).min(1).max(10),
|
|
136
|
+
ref: z.string().optional(),
|
|
137
|
+
selector: z.string().optional(),
|
|
138
|
+
tabId: tabId.optional(),
|
|
139
|
+
},
|
|
140
|
+
timeoutMs: 60_000,
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
name: "upload_image",
|
|
144
|
+
description:
|
|
145
|
+
"Push an image into the page: sets it on a file input if the target is one, otherwise dispatches a paste " +
|
|
146
|
+
"(and drop) event with the image on the target element or the currently focused element — works with most " +
|
|
147
|
+
"rich-text/chat editors.",
|
|
148
|
+
inputSchema: {
|
|
149
|
+
data: z.string().describe("Image content, base64-encoded"),
|
|
150
|
+
mimeType: z.string().optional().describe("Image MIME type (default image/png)"),
|
|
151
|
+
name: z.string().optional().describe("File name to present (default image.png)"),
|
|
152
|
+
ref: z.string().optional(),
|
|
153
|
+
selector: z.string().optional(),
|
|
154
|
+
tabId: tabId.optional(),
|
|
155
|
+
},
|
|
156
|
+
timeoutMs: 30_000,
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
name: "javascript_execute",
|
|
160
|
+
description:
|
|
161
|
+
"Run JavaScript in the page's main world (same context as the site's own scripts) and return the result. " +
|
|
162
|
+
"The final expression's value is returned if JSON-serializable. Use sparingly — prefer read_page/find/form_input.",
|
|
163
|
+
inputSchema: {
|
|
164
|
+
code: z.string().describe("JavaScript source to evaluate, e.g. \"document.title\""),
|
|
165
|
+
awaitPromise: z.boolean().optional().describe("Wait for a returned Promise to settle (default true)"),
|
|
166
|
+
tabId: tabId.optional(),
|
|
167
|
+
},
|
|
168
|
+
timeoutMs: 30_000,
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
name: "read_console_messages",
|
|
172
|
+
description:
|
|
173
|
+
"Read console output (console.*, errors, warnings) captured from the tab. Capture is CDP-based, so it covers " +
|
|
174
|
+
"messages emitted while TaskWindow has been driving the tab.",
|
|
175
|
+
inputSchema: {
|
|
176
|
+
tabId: tabId.optional(),
|
|
177
|
+
pattern: z.string().optional().describe("Only messages matching this regular expression"),
|
|
178
|
+
level: z.enum(["log", "info", "warning", "error"]).optional().describe("Minimum severity to include"),
|
|
179
|
+
limit: z.number().int().min(1).max(1000).optional().describe("Max messages to return (default 200, newest last)"),
|
|
180
|
+
},
|
|
181
|
+
timeoutMs: 20_000,
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
name: "read_network_requests",
|
|
185
|
+
description:
|
|
186
|
+
"Read network requests observed in the tab while TaskWindow was attached: method, URL, status, type and size.",
|
|
187
|
+
inputSchema: {
|
|
188
|
+
tabId: tabId.optional(),
|
|
189
|
+
pattern: z.string().optional().describe("Only requests whose URL matches this regular expression"),
|
|
190
|
+
limit: z.number().int().min(1).max(1000).optional().describe("Max requests to return (default 200, newest last)"),
|
|
191
|
+
},
|
|
192
|
+
timeoutMs: 20_000,
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
name: "browser_batch",
|
|
196
|
+
description:
|
|
197
|
+
"Run several browser tool calls in one round trip, in order, on the same tab context. Aborts on the first " +
|
|
198
|
+
"failing step. Each step is {tool, params} where tool is any TaskWindow browser tool except browser_batch. " +
|
|
199
|
+
"Tip: a common batch is navigate followed by a computer wait then read_page.",
|
|
200
|
+
inputSchema: {
|
|
201
|
+
steps: z.array(z.object({
|
|
202
|
+
tool: z.string(),
|
|
203
|
+
params: z.record(z.any()).optional().default({}),
|
|
204
|
+
})).min(1).max(20),
|
|
205
|
+
},
|
|
206
|
+
timeoutMs: 300_000,
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
name: "gif_record",
|
|
210
|
+
description:
|
|
211
|
+
"Record a GIF of the tab for `duration` seconds (captures CDP screenshots at `fps` and encodes GIF89a in an " +
|
|
212
|
+
"offscreen document). Returns the GIF as base64. Use to document a multi-step interaction.",
|
|
213
|
+
inputSchema: {
|
|
214
|
+
tabId: tabId.optional(),
|
|
215
|
+
duration: z.number().min(0.5).max(30).describe("Seconds to record (max 30)"),
|
|
216
|
+
fps: z.number().min(1).max(10).optional().describe("Frames per second (default 5)"),
|
|
217
|
+
maxWidth: z.number().int().min(100).max(1280).optional().describe("Downscale frames to at most this width (default 800)"),
|
|
218
|
+
},
|
|
219
|
+
timeoutMs: 180_000,
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
name: "shortcuts_list",
|
|
223
|
+
description: "List the extension-defined shortcut macros (named sequences of tool actions).",
|
|
224
|
+
inputSchema: {},
|
|
225
|
+
timeoutMs: 10_000,
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
name: "shortcuts_execute",
|
|
229
|
+
description: "Run a shortcut macro defined in the extension and return each action's result.",
|
|
230
|
+
inputSchema: { name: z.string().min(1) },
|
|
231
|
+
timeoutMs: 120_000,
|
|
232
|
+
},
|
|
233
|
+
];
|
|
234
|
+
|
|
235
|
+
const toolNames = new Set(toolDefs.map((t) => t.name));
|
|
236
|
+
|
|
237
|
+
function toMcpResult(result) {
|
|
238
|
+
const content = [];
|
|
239
|
+
if (result && typeof result === "object" && result.image) {
|
|
240
|
+
content.push({
|
|
241
|
+
type: "image",
|
|
242
|
+
data: result.image.data,
|
|
243
|
+
mimeType: result.image.mimeType || "image/png",
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
let text;
|
|
247
|
+
if (result && typeof result === "object") {
|
|
248
|
+
if (typeof result.text === "string") text = result.text;
|
|
249
|
+
else if ("data" in result) text = JSON.stringify(result.data, null, 2);
|
|
250
|
+
else text = JSON.stringify(result, null, 2);
|
|
251
|
+
} else {
|
|
252
|
+
text = String(result);
|
|
253
|
+
}
|
|
254
|
+
content.push({ type: "text", text });
|
|
255
|
+
return { content };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function registerTools(server, { bridge, logger = console }) {
|
|
259
|
+
for (const def of toolDefs) {
|
|
260
|
+
server.registerTool(def.name, { description: def.description, inputSchema: def.inputSchema }, async (args) => {
|
|
261
|
+
try {
|
|
262
|
+
if (def.name === "browser_batch") return await runBatch(args, bridge, logger);
|
|
263
|
+
const result = await bridge.sendTool(def.name, args, def.timeoutMs);
|
|
264
|
+
return toMcpResult(result);
|
|
265
|
+
} catch (err) {
|
|
266
|
+
logger.error(`[mcp] ${def.name} failed:`, err.message);
|
|
267
|
+
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function runBatch({ steps }, bridge, logger) {
|
|
274
|
+
const results = [];
|
|
275
|
+
for (let i = 0; i < steps.length; i++) {
|
|
276
|
+
const { tool, params } = steps[i];
|
|
277
|
+
if (!toolNames.has(tool)) {
|
|
278
|
+
return {
|
|
279
|
+
content: [{ type: "text", text: `Error: step ${i + 1}: unknown tool "${tool}"` }],
|
|
280
|
+
isError: true,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
if (tool === "browser_batch") {
|
|
284
|
+
return {
|
|
285
|
+
content: [{ type: "text", text: `Error: step ${i + 1}: browser_batch cannot be nested` }],
|
|
286
|
+
isError: true,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
const def = toolDefs.find((d) => d.name === tool);
|
|
291
|
+
const result = await bridge.sendTool(tool, params, def.timeoutMs);
|
|
292
|
+
results.push({ step: i + 1, tool, ok: true, result });
|
|
293
|
+
} catch (err) {
|
|
294
|
+
logger.error(`[mcp] batch step ${i + 1} (${tool}) failed:`, err.message);
|
|
295
|
+
const summary = results.map((r) => `${r.step}. ${r.tool}: ok`).join("\n");
|
|
296
|
+
return {
|
|
297
|
+
content: [{
|
|
298
|
+
type: "text",
|
|
299
|
+
text: `Error: batch aborted at step ${i + 1} (${tool}): ${err.message}\n` +
|
|
300
|
+
`Completed steps:\n${summary || "(none)"}`,
|
|
301
|
+
}],
|
|
302
|
+
isError: true,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return toMcpResult({
|
|
307
|
+
text: results
|
|
308
|
+
.map((r) => {
|
|
309
|
+
const body = r.result && typeof r.result.text === "string"
|
|
310
|
+
? r.result.text
|
|
311
|
+
: JSON.stringify(r.result?.data ?? r.result ?? null, null, 2);
|
|
312
|
+
return `${r.step}. ${r.tool}:\n${body}`;
|
|
313
|
+
})
|
|
314
|
+
.join("\n\n"),
|
|
315
|
+
data: results.map((r) => ({ tool: r.tool, ok: true })),
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export { toolDefs };
|