vite-plugin-opencode-assistant 1.1.24 → 1.1.26
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/es/core/mcp-chrome.d.ts +43 -0
- package/es/core/mcp-chrome.mjs +147 -0
- package/es/core/mcp-proxy.d.ts +21 -0
- package/es/core/mcp-proxy.mjs +254 -0
- package/es/core/opencode-web.d.ts +1 -1
- package/es/core/opencode-web.mjs +4 -4
- package/es/core/service.d.ts +2 -1
- package/es/core/service.mjs +4 -3
- package/es/endpoints/context.mjs +7 -2
- package/es/endpoints/index.d.ts +4 -2
- package/es/endpoints/index.mjs +4 -1
- package/es/endpoints/mcp-tools.d.ts +17 -0
- package/es/endpoints/mcp-tools.mjs +519 -0
- package/es/endpoints/mcp.d.ts +6 -0
- package/es/endpoints/mcp.mjs +290 -0
- package/es/index.mjs +71 -66
- package/lib/client.js +564 -563
- package/lib/core/mcp-chrome.cjs +174 -0
- package/lib/core/mcp-chrome.d.ts +43 -0
- package/lib/core/mcp-proxy.cjs +286 -0
- package/lib/core/mcp-proxy.d.ts +21 -0
- package/lib/core/opencode-web.cjs +4 -4
- package/lib/core/opencode-web.d.ts +1 -1
- package/lib/core/service.cjs +4 -3
- package/lib/core/service.d.ts +2 -1
- package/lib/endpoints/context.cjs +7 -2
- package/lib/endpoints/index.cjs +5 -1
- package/lib/endpoints/index.d.ts +4 -2
- package/lib/endpoints/mcp-tools.cjs +541 -0
- package/lib/endpoints/mcp-tools.d.ts +17 -0
- package/lib/endpoints/mcp.cjs +307 -0
- package/lib/endpoints/mcp.d.ts +6 -0
- package/lib/index.cjs +71 -66
- package/package.json +6 -5
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Chrome 页面相关工具
|
|
3
|
+
*
|
|
4
|
+
* 专注于 Chrome DevTools 页面匹配与解析逻辑
|
|
5
|
+
*/
|
|
6
|
+
import type { ViteDevServer } from "vite";
|
|
7
|
+
import type { McpProxy } from "./mcp-proxy";
|
|
8
|
+
/** 从 Vite 服务器解析的所有 URL 中提取项目 origin 列表 */
|
|
9
|
+
export declare function getProjectOrigins(server: ViteDevServer): string[];
|
|
10
|
+
/** 判断页面 URL 是否属于项目的某个 origin */
|
|
11
|
+
export declare function isProjectPage(url: string, origins: string[]): boolean;
|
|
12
|
+
export interface PageInfo {
|
|
13
|
+
pageId: number;
|
|
14
|
+
url: string;
|
|
15
|
+
title: string;
|
|
16
|
+
/** Chrome DevTools 当前选中的页面 */
|
|
17
|
+
selected: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** 解析 list_pages 返回的文本。格式:"56: Title (URL) [selected]" */
|
|
20
|
+
export declare function parseListPages(text: string): PageInfo[];
|
|
21
|
+
/** 从 evaluate_script 返回的格式化文本中提取 JSON 值 */
|
|
22
|
+
export declare function extractEvalValue(text: string | undefined): string | undefined;
|
|
23
|
+
type PageIdResult = {
|
|
24
|
+
ok: true;
|
|
25
|
+
pageId: number;
|
|
26
|
+
} | {
|
|
27
|
+
ok: false;
|
|
28
|
+
error: string;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* 通过 MCP 解析当前页面对应的 Chrome DevTools pageId
|
|
32
|
+
*
|
|
33
|
+
* 策略:
|
|
34
|
+
* 1. list_pages → 解析每行的 "pageId: title (URL)" 格式
|
|
35
|
+
* 2. 优先用 sessionId 匹配(跨导航可靠,遍历所有页面 evaluate_script)
|
|
36
|
+
* 3. 无 sessionId 时降级为 URL 精确匹配
|
|
37
|
+
*
|
|
38
|
+
* 失败时返回具体原因,由调用方透传给 Agent。
|
|
39
|
+
*/
|
|
40
|
+
export declare function resolveChromePageId(mcp: McpProxy | undefined, url: string, title: string, projectOrigins: string[], sessionId?: string, pages?: PageInfo[],
|
|
41
|
+
/** Chrome 当前选中的 pageId(调用方传入,避免过滤后丢失非项目页面信息) */
|
|
42
|
+
chromeSelectedPageId?: number): Promise<PageIdResult>;
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
var __async = (__this, __arguments, generator) => {
|
|
2
|
+
return new Promise((resolve, reject) => {
|
|
3
|
+
var fulfilled = (value) => {
|
|
4
|
+
try {
|
|
5
|
+
step(generator.next(value));
|
|
6
|
+
} catch (e) {
|
|
7
|
+
reject(e);
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var rejected = (value) => {
|
|
11
|
+
try {
|
|
12
|
+
step(generator.throw(value));
|
|
13
|
+
} catch (e) {
|
|
14
|
+
reject(e);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
18
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
import { createLogger } from "@vite-plugin-opencode-assistant/shared/node";
|
|
22
|
+
const log = createLogger("McpChrome");
|
|
23
|
+
function getProjectOrigins(server) {
|
|
24
|
+
var _a, _b, _c, _d;
|
|
25
|
+
const local = (_b = (_a = server.resolvedUrls) == null ? void 0 : _a.local) != null ? _b : [];
|
|
26
|
+
const network = (_d = (_c = server.resolvedUrls) == null ? void 0 : _c.network) != null ? _d : [];
|
|
27
|
+
const origins = [...new Set([...local, ...network].map((u) => new URL(u).origin))];
|
|
28
|
+
log.debug("project origins", { origins });
|
|
29
|
+
return origins;
|
|
30
|
+
}
|
|
31
|
+
function isProjectPage(url, origins) {
|
|
32
|
+
return origins.some((origin) => url.startsWith(origin));
|
|
33
|
+
}
|
|
34
|
+
function parseListPages(text) {
|
|
35
|
+
const pages = [];
|
|
36
|
+
for (const line of text.split("\n")) {
|
|
37
|
+
const match = line.match(/^(\d+):\s*(.+?)\s*\((\S+)\)/);
|
|
38
|
+
if (match) {
|
|
39
|
+
pages.push({
|
|
40
|
+
pageId: parseInt(match[1], 10),
|
|
41
|
+
title: match[2].replace(/\s*\.{3}$/, "").trim(),
|
|
42
|
+
url: match[3],
|
|
43
|
+
selected: /\[selected\]/i.test(line)
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return pages;
|
|
48
|
+
}
|
|
49
|
+
function extractEvalValue(text) {
|
|
50
|
+
if (!text) return void 0;
|
|
51
|
+
const marker = "```json\n";
|
|
52
|
+
const startIdx = text.indexOf(marker);
|
|
53
|
+
if (startIdx < 0) return text.trim();
|
|
54
|
+
const contentStart = startIdx + marker.length;
|
|
55
|
+
const endIdx = text.indexOf("\n```", contentStart);
|
|
56
|
+
const jsonStr = endIdx < 0 ? text.substring(contentStart) : text.substring(contentStart, endIdx);
|
|
57
|
+
try {
|
|
58
|
+
return JSON.parse(jsonStr.trim());
|
|
59
|
+
} catch (e) {
|
|
60
|
+
return jsonStr.trim();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function resolveChromePageId(mcp, url, title, projectOrigins, sessionId, pages, chromeSelectedPageId) {
|
|
64
|
+
return __async(this, null, function* () {
|
|
65
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
66
|
+
if (!mcp || !mcp.isRunning) {
|
|
67
|
+
const reason = !mcp ? "MCP \u6A21\u5757\u672A\u521D\u59CB\u5316" : "Chrome DevTools MCP \u8FDB\u7A0B\u672A\u542F\u52A8";
|
|
68
|
+
log.debug(`resolveChromePageId: ${reason}`);
|
|
69
|
+
return { ok: false, error: reason };
|
|
70
|
+
}
|
|
71
|
+
if (!url) {
|
|
72
|
+
return { ok: false, error: "\u9875\u9762 URL \u4E3A\u7A7A\uFF0C\u5C1A\u672A\u6536\u5230\u4E0A\u4E0B\u6587\u4FE1\u606F" };
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
if (!pages) {
|
|
76
|
+
const listResult = yield mcp.callChromeDevTool("list_pages", {});
|
|
77
|
+
const text = (_c = (_b = (_a = listResult == null ? void 0 : listResult.result) == null ? void 0 : _a.content) == null ? void 0 : _b[0]) == null ? void 0 : _c.text;
|
|
78
|
+
if (!text) {
|
|
79
|
+
return { ok: false, error: "\u65E0\u6CD5\u83B7\u53D6 Chrome \u9875\u9762\u5217\u8868\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u6253\u5F00\u76EE\u6807\u9875\u9762" };
|
|
80
|
+
}
|
|
81
|
+
const allPages = parseListPages(text);
|
|
82
|
+
chromeSelectedPageId = (_d = allPages.find((p) => p.selected)) == null ? void 0 : _d.pageId;
|
|
83
|
+
pages = allPages.filter((p) => isProjectPage(p.url, projectOrigins));
|
|
84
|
+
}
|
|
85
|
+
log.debug("resolveChromePageId: list_pages result", {
|
|
86
|
+
pages: pages.map((p) => ({ id: p.pageId, url: p.url, title: p.title.substring(0, 40) })),
|
|
87
|
+
target: { url, title }
|
|
88
|
+
});
|
|
89
|
+
const normalizeUrl = (u) => u.replace(/\/$/, "");
|
|
90
|
+
const targetUrl = normalizeUrl(url);
|
|
91
|
+
if (sessionId) {
|
|
92
|
+
let matchedPageId = null;
|
|
93
|
+
for (const page of pages) {
|
|
94
|
+
yield mcp.callChromeDevTool("select_page", { pageId: page.pageId, bringToFront: false });
|
|
95
|
+
const evalResult = yield mcp.callChromeDevTool("evaluate_script", {
|
|
96
|
+
function: "() => sessionStorage.getItem('_opencode_pk')"
|
|
97
|
+
});
|
|
98
|
+
const rawText = (_g = (_f = (_e = evalResult == null ? void 0 : evalResult.result) == null ? void 0 : _e.content) == null ? void 0 : _f[0]) == null ? void 0 : _g.text;
|
|
99
|
+
const extracted = extractEvalValue(rawText);
|
|
100
|
+
if (extracted === sessionId) {
|
|
101
|
+
matchedPageId = page.pageId;
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (chromeSelectedPageId != null && chromeSelectedPageId !== matchedPageId) {
|
|
106
|
+
yield mcp.callChromeDevTool("select_page", {
|
|
107
|
+
pageId: chromeSelectedPageId,
|
|
108
|
+
bringToFront: false
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
if (matchedPageId != null) {
|
|
112
|
+
return { ok: true, pageId: matchedPageId };
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
ok: false,
|
|
116
|
+
error: `\u672A\u80FD\u901A\u8FC7\u4F1A\u8BDD\u6807\u8BC6\u627E\u5230\u76EE\u6807\u9875\u9762\uFF0C\u8BF7\u786E\u8BA4\u76EE\u6807\u9875\u9762\u5DF2\u6253\u5F00`
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
const matches = pages.filter((p) => normalizeUrl(p.url) === targetUrl);
|
|
120
|
+
if (matches.length === 0) {
|
|
121
|
+
return {
|
|
122
|
+
ok: false,
|
|
123
|
+
error: `Chrome \u4E2D\u672A\u627E\u5230\u5339\u914D\u7684\u9875\u9762 (${targetUrl})\uFF0C\u8BF7\u786E\u8BA4\u672C\u5730\u5F00\u53D1\u9875\u9762\u5DF2\u5728 Chrome DevTools \u4E2D\u6253\u5F00`
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (matches.length === 1) {
|
|
127
|
+
log.debug("resolveChromePageId: URL matched", { pageId: matches[0].pageId });
|
|
128
|
+
return { ok: true, pageId: matches[0].pageId };
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
ok: false,
|
|
132
|
+
error: `\u5B58\u5728 ${matches.length} \u4E2A\u540C URL \u7684\u9875\u9762\uFF0C\u7F3A\u5C11\u9875\u9762\u6807\u8BC6\u65E0\u6CD5\u533A\u5206\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5`
|
|
133
|
+
};
|
|
134
|
+
} catch (err) {
|
|
135
|
+
const msg = `MCP \u8C03\u7528\u5931\u8D25: ${err.message}`;
|
|
136
|
+
log.debug("Failed to resolve pageId via MCP", { error: err.message });
|
|
137
|
+
return { ok: false, error: msg };
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
export {
|
|
142
|
+
extractEvalValue,
|
|
143
|
+
getProjectOrigins,
|
|
144
|
+
isProjectPage,
|
|
145
|
+
parseListPages,
|
|
146
|
+
resolveChromePageId
|
|
147
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface McpProxyOptions {
|
|
2
|
+
args?: string[];
|
|
3
|
+
idleTimeout?: number;
|
|
4
|
+
}
|
|
5
|
+
export declare class McpProxy {
|
|
6
|
+
#private;
|
|
7
|
+
readonly sessionId: string;
|
|
8
|
+
readonly accessToken: string;
|
|
9
|
+
constructor(options?: McpProxyOptions);
|
|
10
|
+
get isRunning(): boolean;
|
|
11
|
+
start(): Promise<void>;
|
|
12
|
+
/** 转发原始 JSON-RPC 请求,保留客户端 ID */
|
|
13
|
+
forward(rawRequest: string): Promise<string>;
|
|
14
|
+
/** 调用 MCP 工具 */
|
|
15
|
+
call(method: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
16
|
+
/** 直接调用 chrome-devtools-mcp 底层工具(内部使用) */
|
|
17
|
+
callChromeDevTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
|
|
18
|
+
/** 验证 MCP 是否可用 + 预热 CDP 连接 */
|
|
19
|
+
verify(): Promise<boolean>;
|
|
20
|
+
stop(): void;
|
|
21
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __typeError = (msg) => {
|
|
3
|
+
throw TypeError(msg);
|
|
4
|
+
};
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
7
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
8
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
9
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
10
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
11
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
12
|
+
var __privateWrapper = (obj, member, setter, getter) => ({
|
|
13
|
+
set _(value) {
|
|
14
|
+
__privateSet(obj, member, value, setter);
|
|
15
|
+
},
|
|
16
|
+
get _() {
|
|
17
|
+
return __privateGet(obj, member, getter);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
var __async = (__this, __arguments, generator) => {
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
var fulfilled = (value) => {
|
|
23
|
+
try {
|
|
24
|
+
step(generator.next(value));
|
|
25
|
+
} catch (e) {
|
|
26
|
+
reject(e);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var rejected = (value) => {
|
|
30
|
+
try {
|
|
31
|
+
step(generator.throw(value));
|
|
32
|
+
} catch (e) {
|
|
33
|
+
reject(e);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
37
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
38
|
+
});
|
|
39
|
+
};
|
|
40
|
+
const import_meta = {};
|
|
41
|
+
var _proc, _rl, _messageId, _internalIdBase, _pending, _args, _startPromise, _idleTimer, _idleTimeout, _McpProxy_instances, doStart_fn, resetIdleTimer_fn;
|
|
42
|
+
import { spawn } from "node:child_process";
|
|
43
|
+
import { createInterface } from "node:readline";
|
|
44
|
+
import crypto from "node:crypto";
|
|
45
|
+
import { createRequire } from "node:module";
|
|
46
|
+
import path from "node:path";
|
|
47
|
+
import { createLogger } from "@vite-plugin-opencode-assistant/shared/node";
|
|
48
|
+
const log = createLogger("McpProxy");
|
|
49
|
+
function resolveChromeDevToolsMcpBin() {
|
|
50
|
+
const require2 = createRequire(import_meta.url);
|
|
51
|
+
const pkgJsonPath = require2.resolve("chrome-devtools-mcp/package.json");
|
|
52
|
+
const pkgDir = path.dirname(pkgJsonPath);
|
|
53
|
+
const { bin } = require2(pkgJsonPath);
|
|
54
|
+
const binEntry = typeof bin === "string" ? bin : Object.values(bin)[0];
|
|
55
|
+
return path.resolve(pkgDir, binEntry);
|
|
56
|
+
}
|
|
57
|
+
class McpProxy {
|
|
58
|
+
constructor(options = {}) {
|
|
59
|
+
__privateAdd(this, _McpProxy_instances);
|
|
60
|
+
__privateAdd(this, _proc, null);
|
|
61
|
+
__privateAdd(this, _rl, null);
|
|
62
|
+
__privateAdd(this, _messageId, 0);
|
|
63
|
+
/** 内部调用使用的高位 ID 起始值,避免与客户端 ID 冲突 */
|
|
64
|
+
__privateAdd(this, _internalIdBase, 1e6);
|
|
65
|
+
__privateAdd(this, _pending, /* @__PURE__ */ new Map());
|
|
66
|
+
__privateAdd(this, _args);
|
|
67
|
+
__privateAdd(this, _startPromise, null);
|
|
68
|
+
__privateAdd(this, _idleTimer, null);
|
|
69
|
+
__privateAdd(this, _idleTimeout);
|
|
70
|
+
__publicField(this, "sessionId");
|
|
71
|
+
__publicField(this, "accessToken");
|
|
72
|
+
var _a, _b;
|
|
73
|
+
__privateSet(this, _args, (_a = options.args) != null ? _a : ["--auto-connect", "--no-usage-statistics"]);
|
|
74
|
+
__privateSet(this, _idleTimeout, (_b = options.idleTimeout) != null ? _b : 0);
|
|
75
|
+
this.sessionId = crypto.randomUUID();
|
|
76
|
+
this.accessToken = crypto.randomBytes(32).toString("hex");
|
|
77
|
+
}
|
|
78
|
+
get isRunning() {
|
|
79
|
+
return __privateGet(this, _proc) !== null && !__privateGet(this, _proc).killed;
|
|
80
|
+
}
|
|
81
|
+
start() {
|
|
82
|
+
return __async(this, null, function* () {
|
|
83
|
+
if (this.isRunning) return;
|
|
84
|
+
if (__privateGet(this, _startPromise)) return __privateGet(this, _startPromise);
|
|
85
|
+
__privateSet(this, _startPromise, __privateMethod(this, _McpProxy_instances, doStart_fn).call(this));
|
|
86
|
+
return __privateGet(this, _startPromise);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/** 转发原始 JSON-RPC 请求,保留客户端 ID */
|
|
90
|
+
forward(rawRequest) {
|
|
91
|
+
return __async(this, null, function* () {
|
|
92
|
+
yield this.start();
|
|
93
|
+
if (!__privateGet(this, _proc) || !__privateGet(this, _proc).stdin) {
|
|
94
|
+
throw new Error("MCP process not available");
|
|
95
|
+
}
|
|
96
|
+
__privateMethod(this, _McpProxy_instances, resetIdleTimer_fn).call(this);
|
|
97
|
+
let msg;
|
|
98
|
+
try {
|
|
99
|
+
msg = JSON.parse(rawRequest);
|
|
100
|
+
} catch (e) {
|
|
101
|
+
throw new Error("Invalid JSON-RPC request");
|
|
102
|
+
}
|
|
103
|
+
return new Promise((resolve, reject) => {
|
|
104
|
+
const id = msg.id;
|
|
105
|
+
if (id !== void 0) {
|
|
106
|
+
__privateGet(this, _pending).set(id, (raw) => resolve(JSON.stringify(raw)));
|
|
107
|
+
} else {
|
|
108
|
+
__privateGet(this, _proc).stdin.write(rawRequest + "\n");
|
|
109
|
+
resolve("");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
__privateGet(this, _proc).stdin.write(rawRequest + "\n");
|
|
113
|
+
setTimeout(() => {
|
|
114
|
+
if (__privateGet(this, _pending).has(id)) {
|
|
115
|
+
__privateGet(this, _pending).delete(id);
|
|
116
|
+
reject(new Error("MCP forward timeout"));
|
|
117
|
+
}
|
|
118
|
+
}, 3e4);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** 调用 MCP 工具 */
|
|
123
|
+
call(_0) {
|
|
124
|
+
return __async(this, arguments, function* (method, params = {}) {
|
|
125
|
+
yield this.start();
|
|
126
|
+
if (!__privateGet(this, _proc) || !__privateGet(this, _proc).stdin) {
|
|
127
|
+
throw new Error("MCP process not available");
|
|
128
|
+
}
|
|
129
|
+
__privateMethod(this, _McpProxy_instances, resetIdleTimer_fn).call(this);
|
|
130
|
+
const id = __privateGet(this, _internalIdBase) + ++__privateWrapper(this, _messageId)._;
|
|
131
|
+
return new Promise((resolve, reject) => {
|
|
132
|
+
__privateGet(this, _pending).set(id, resolve);
|
|
133
|
+
const request = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
134
|
+
__privateGet(this, _proc).stdin.write(request + "\n");
|
|
135
|
+
setTimeout(() => {
|
|
136
|
+
if (__privateGet(this, _pending).has(id)) {
|
|
137
|
+
__privateGet(this, _pending).delete(id);
|
|
138
|
+
reject(new Error(`MCP call timeout: ${method}`));
|
|
139
|
+
}
|
|
140
|
+
}, 3e4);
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/** 直接调用 chrome-devtools-mcp 底层工具(内部使用) */
|
|
145
|
+
callChromeDevTool(_0) {
|
|
146
|
+
return __async(this, arguments, function* (name, args = {}) {
|
|
147
|
+
return this.call("tools/call", { name, arguments: args });
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/** 验证 MCP 是否可用 + 预热 CDP 连接 */
|
|
151
|
+
verify() {
|
|
152
|
+
return __async(this, null, function* () {
|
|
153
|
+
try {
|
|
154
|
+
yield this.callChromeDevTool("list_pages", {});
|
|
155
|
+
return true;
|
|
156
|
+
} catch (e) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
stop() {
|
|
162
|
+
if (__privateGet(this, _idleTimer)) clearTimeout(__privateGet(this, _idleTimer));
|
|
163
|
+
const err = new Error("MCP server shutting down");
|
|
164
|
+
for (const resolve of __privateGet(this, _pending).values()) {
|
|
165
|
+
resolve({ error: { code: -32e3, message: err.message } });
|
|
166
|
+
}
|
|
167
|
+
__privateGet(this, _pending).clear();
|
|
168
|
+
if (__privateGet(this, _rl)) {
|
|
169
|
+
__privateGet(this, _rl).close();
|
|
170
|
+
__privateSet(this, _rl, null);
|
|
171
|
+
}
|
|
172
|
+
if (__privateGet(this, _proc) && !__privateGet(this, _proc).killed) {
|
|
173
|
+
__privateGet(this, _proc).kill();
|
|
174
|
+
__privateSet(this, _proc, null);
|
|
175
|
+
}
|
|
176
|
+
__privateSet(this, _startPromise, null);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
_proc = new WeakMap();
|
|
180
|
+
_rl = new WeakMap();
|
|
181
|
+
_messageId = new WeakMap();
|
|
182
|
+
_internalIdBase = new WeakMap();
|
|
183
|
+
_pending = new WeakMap();
|
|
184
|
+
_args = new WeakMap();
|
|
185
|
+
_startPromise = new WeakMap();
|
|
186
|
+
_idleTimer = new WeakMap();
|
|
187
|
+
_idleTimeout = new WeakMap();
|
|
188
|
+
_McpProxy_instances = new WeakSet();
|
|
189
|
+
doStart_fn = function() {
|
|
190
|
+
return __async(this, null, function* () {
|
|
191
|
+
var _a;
|
|
192
|
+
log.debug("Starting MCP process", { args: __privateGet(this, _args) });
|
|
193
|
+
try {
|
|
194
|
+
const binPath = resolveChromeDevToolsMcpBin();
|
|
195
|
+
__privateSet(this, _proc, spawn(binPath, __privateGet(this, _args), { stdio: ["pipe", "pipe", "pipe"] }));
|
|
196
|
+
log.debug("Using local chrome-devtools-mcp");
|
|
197
|
+
} catch (e) {
|
|
198
|
+
__privateSet(this, _proc, spawn("npx", ["-y", "chrome-devtools-mcp@latest", ...__privateGet(this, _args)], {
|
|
199
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
200
|
+
}));
|
|
201
|
+
}
|
|
202
|
+
__privateSet(this, _rl, createInterface({ input: __privateGet(this, _proc).stdout }));
|
|
203
|
+
__privateGet(this, _rl).on("line", (line) => {
|
|
204
|
+
try {
|
|
205
|
+
const msg = JSON.parse(line);
|
|
206
|
+
log.debug("MCP stdout", {
|
|
207
|
+
id: msg.id,
|
|
208
|
+
method: msg.method,
|
|
209
|
+
hasResult: !!msg.result,
|
|
210
|
+
hasError: !!msg.error
|
|
211
|
+
});
|
|
212
|
+
if (msg.id !== void 0 && __privateGet(this, _pending).has(msg.id)) {
|
|
213
|
+
const resolve = __privateGet(this, _pending).get(msg.id);
|
|
214
|
+
__privateGet(this, _pending).delete(msg.id);
|
|
215
|
+
log.debug("MCP pending resolved", { id: msg.id });
|
|
216
|
+
resolve(msg);
|
|
217
|
+
}
|
|
218
|
+
} catch (e) {
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
(_a = __privateGet(this, _proc).stderr) == null ? void 0 : _a.on("data", (d) => {
|
|
222
|
+
const text = d.toString().trim();
|
|
223
|
+
if (text) log.debug("[MCP stderr]", { text: text.substring(0, 200) });
|
|
224
|
+
});
|
|
225
|
+
__privateGet(this, _proc).on("close", (code) => {
|
|
226
|
+
log.debug("MCP process closed", { code });
|
|
227
|
+
for (const resolve of __privateGet(this, _pending).values()) {
|
|
228
|
+
resolve({ error: { code: -32e3, message: `MCP process exited with code ${code}` } });
|
|
229
|
+
}
|
|
230
|
+
__privateGet(this, _pending).clear();
|
|
231
|
+
__privateSet(this, _proc, null);
|
|
232
|
+
__privateSet(this, _rl, null);
|
|
233
|
+
__privateSet(this, _startPromise, null);
|
|
234
|
+
});
|
|
235
|
+
yield this.call("initialize", {
|
|
236
|
+
protocolVersion: "2024-11-05",
|
|
237
|
+
capabilities: {},
|
|
238
|
+
clientInfo: { name: "vite-plugin-opencode", version: "1.0.0" }
|
|
239
|
+
});
|
|
240
|
+
log.debug("MCP proxy ready");
|
|
241
|
+
__privateSet(this, _startPromise, null);
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
resetIdleTimer_fn = function() {
|
|
245
|
+
if (__privateGet(this, _idleTimeout) <= 0) return;
|
|
246
|
+
if (__privateGet(this, _idleTimer)) clearTimeout(__privateGet(this, _idleTimer));
|
|
247
|
+
__privateSet(this, _idleTimer, setTimeout(() => {
|
|
248
|
+
log.debug("MCP process idle timeout, stopping");
|
|
249
|
+
this.stop();
|
|
250
|
+
}, __privateGet(this, _idleTimeout)));
|
|
251
|
+
};
|
|
252
|
+
export {
|
|
253
|
+
McpProxy
|
|
254
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { ResultPromise } from "execa";
|
|
2
2
|
import type { WebOptions } from "@vite-plugin-opencode-assistant/shared";
|
|
3
|
-
export declare function prepareOpenCodeRuntime(cwd: string): string;
|
|
3
|
+
export declare function prepareOpenCodeRuntime(cwd: string, vitePort: number, mcpToken: string): string;
|
|
4
4
|
export declare function startOpenCodeWeb(options: WebOptions): ResultPromise;
|
package/es/core/opencode-web.mjs
CHANGED
|
@@ -22,11 +22,12 @@ import fs from "fs";
|
|
|
22
22
|
import { createRequire } from "module";
|
|
23
23
|
import path from "path";
|
|
24
24
|
import { pathToFileURL } from "url";
|
|
25
|
+
import { MCP_API_PATH } from "@vite-plugin-opencode-assistant/shared";
|
|
25
26
|
import { createLogger, getProcessLogBuffer } from "@vite-plugin-opencode-assistant/shared/node";
|
|
26
27
|
const require2 = createRequire(path.join(process.cwd(), "package.json"));
|
|
27
28
|
const packageDir = resolvePackageDir();
|
|
28
29
|
const log = createLogger("OpenCodeWeb");
|
|
29
|
-
function prepareOpenCodeRuntime(cwd) {
|
|
30
|
+
function prepareOpenCodeRuntime(cwd, vitePort, mcpToken) {
|
|
30
31
|
const cacheDir = path.join(cwd, "node_modules", ".cache", "opencode");
|
|
31
32
|
log.debug("Setting up OpenCode runtime", { cacheDir });
|
|
32
33
|
if (!fs.existsSync(cacheDir)) {
|
|
@@ -42,9 +43,8 @@ function prepareOpenCodeRuntime(cwd) {
|
|
|
42
43
|
plugin: plugins,
|
|
43
44
|
mcp: {
|
|
44
45
|
"chrome-devtools": {
|
|
45
|
-
type: "
|
|
46
|
-
|
|
47
|
-
enabled: true
|
|
46
|
+
type: "remote",
|
|
47
|
+
url: `http://localhost:${vitePort}${MCP_API_PATH}?token=${mcpToken}`
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
},
|
package/es/core/service.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { ModelInfo } from "@vite-plugin-opencode-assistant/shared";
|
|
|
4
4
|
import type { OpenCodeOptions, ServiceStartupTask } from "@vite-plugin-opencode-assistant/shared";
|
|
5
5
|
import { ChromeMcpWarmupErrorType } from "@vite-plugin-opencode-assistant/shared";
|
|
6
6
|
import type { OpenCodeAPI } from "./api";
|
|
7
|
+
import type { McpProxy } from "./mcp-proxy";
|
|
7
8
|
export declare class OpenCodeService {
|
|
8
9
|
private config;
|
|
9
10
|
private api;
|
|
@@ -26,7 +27,7 @@ export declare class OpenCodeService {
|
|
|
26
27
|
workspaceRoot: string | null;
|
|
27
28
|
constructor(config: Required<OpenCodeOptions>, api: OpenCodeAPI, sseClients: Set<http.ServerResponse>, onPortAllocated: (port: number) => void, onProxyPortAllocated: (port: number) => void);
|
|
28
29
|
private sendTaskUpdate;
|
|
29
|
-
start(corsOrigins
|
|
30
|
+
start(mcpToken: string, vitePort: number, corsOrigins: string[], contextApiUrl: string, logsApiUrl: string, viteOrigin: string, mcp: McpProxy): Promise<void>;
|
|
30
31
|
getAvailableModels(): Promise<ModelInfo[]>;
|
|
31
32
|
retryWarmupChromeMcp(viteOrigin?: string, selectedModel?: {
|
|
32
33
|
providerID: string;
|
package/es/core/service.mjs
CHANGED
|
@@ -87,7 +87,7 @@ class OpenCodeService {
|
|
|
87
87
|
}
|
|
88
88
|
});
|
|
89
89
|
}
|
|
90
|
-
start(corsOrigins, contextApiUrl, logsApiUrl, viteOrigin) {
|
|
90
|
+
start(mcpToken, vitePort, corsOrigins, contextApiUrl, logsApiUrl, viteOrigin, mcp) {
|
|
91
91
|
return __async(this, null, function* () {
|
|
92
92
|
if (this.isStarted && this.webProcess) {
|
|
93
93
|
log.debug("Services already started, skipping");
|
|
@@ -148,7 +148,7 @@ Please install OpenCode first:
|
|
|
148
148
|
this.workspaceRoot = findGitRoot(process.cwd());
|
|
149
149
|
log.debug(`Using workspace root: ${this.workspaceRoot}`);
|
|
150
150
|
this.sendTaskUpdate("preparing_runtime");
|
|
151
|
-
const configDir = prepareOpenCodeRuntime(this.workspaceRoot);
|
|
151
|
+
const configDir = prepareOpenCodeRuntime(this.workspaceRoot, vitePort, mcpToken);
|
|
152
152
|
timer.checkpoint("Plugin setup complete");
|
|
153
153
|
this.sendTaskUpdate("starting_web");
|
|
154
154
|
log.debug("Starting OpenCode Web process...", {
|
|
@@ -238,7 +238,8 @@ Please install OpenCode first:
|
|
|
238
238
|
this.sendTaskUpdate("warming_up_chrome");
|
|
239
239
|
let warmupFailed = false;
|
|
240
240
|
try {
|
|
241
|
-
yield
|
|
241
|
+
const ok = yield mcp.verify();
|
|
242
|
+
if (!ok) throw new Error("MCP tools list returned empty");
|
|
242
243
|
timer.checkpoint("Chrome MCP warmup complete");
|
|
243
244
|
} catch (e) {
|
|
244
245
|
log.warn("Chrome MCP warmup failed", { error: e });
|
package/es/endpoints/context.mjs
CHANGED
|
@@ -36,7 +36,6 @@ function setupContextEndpoint(server, ctx) {
|
|
|
36
36
|
}
|
|
37
37
|
if (req.method === "GET") {
|
|
38
38
|
const pc = ctx.getPageContext();
|
|
39
|
-
log.debug(`[Context] GET \u2192 url=${pc.url} title=${pc.title} tabId=${pc.tabId}`);
|
|
40
39
|
res.writeHead(200);
|
|
41
40
|
res.end(JSON.stringify(pc));
|
|
42
41
|
reqCtx.end(200);
|
|
@@ -67,7 +66,11 @@ function setupContextEndpoint(server, ctx) {
|
|
|
67
66
|
}
|
|
68
67
|
if (req.method === "POST") {
|
|
69
68
|
let body = "";
|
|
70
|
-
req.on("data", (chunk) => body += chunk);
|
|
69
|
+
req.on("data", (chunk) => body += chunk.toString());
|
|
70
|
+
req.on("error", () => {
|
|
71
|
+
res.writeHead(400);
|
|
72
|
+
res.end(JSON.stringify({ error: "Request error" }));
|
|
73
|
+
});
|
|
71
74
|
req.on("end", () => {
|
|
72
75
|
var _a, _b, _c;
|
|
73
76
|
try {
|
|
@@ -77,6 +80,7 @@ function setupContextEndpoint(server, ctx) {
|
|
|
77
80
|
const newCtx = {
|
|
78
81
|
url: data.url || "",
|
|
79
82
|
title: data.title || "",
|
|
83
|
+
sessionId: data.sessionId,
|
|
80
84
|
tabId: (_a = data.tabId) != null ? _a : existing.tabId,
|
|
81
85
|
tabIndex: (_b = data.tabIndex) != null ? _b : existing.tabIndex,
|
|
82
86
|
selectedElements: data.selectedElements || []
|
|
@@ -89,6 +93,7 @@ function setupContextEndpoint(server, ctx) {
|
|
|
89
93
|
tabId,
|
|
90
94
|
url: newCtx.url,
|
|
91
95
|
title: newCtx.title,
|
|
96
|
+
sessionId: newCtx.sessionId,
|
|
92
97
|
selectedElementsCount: ((_c = newCtx.selectedElements) == null ? void 0 : _c.length) || 0
|
|
93
98
|
});
|
|
94
99
|
if (newCtx.selectedElements && newCtx.selectedElements.length > 0) {
|
package/es/endpoints/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { ViteDevServer } from "vite";
|
|
2
2
|
import type { EndpointContext } from "./types";
|
|
3
|
+
import { MCP_API_PATH } from "./mcp";
|
|
4
|
+
import type { McpProxy } from "../core/mcp-proxy";
|
|
3
5
|
import { LOGS_API_PATH } from "@vite-plugin-opencode-assistant/shared";
|
|
4
6
|
export * from "./types";
|
|
5
|
-
export { LOGS_API_PATH };
|
|
6
|
-
export declare function setupMiddlewares(server: ViteDevServer, ctx: EndpointContext): void;
|
|
7
|
+
export { LOGS_API_PATH, MCP_API_PATH };
|
|
8
|
+
export declare function setupMiddlewares(server: ViteDevServer, ctx: EndpointContext, mcp?: McpProxy): void;
|
package/es/endpoints/index.mjs
CHANGED
|
@@ -5,9 +5,10 @@ import { setupSseEndpoint } from "./sse.mjs";
|
|
|
5
5
|
import { setupSessionsEndpoint } from "./sessions.mjs";
|
|
6
6
|
import { setupWarmupEndpoint } from "./warmup.mjs";
|
|
7
7
|
import { setupLogsEndpoint } from "./logs.mjs";
|
|
8
|
+
import { setupMcpEndpoint, MCP_API_PATH } from "./mcp.mjs";
|
|
8
9
|
import { LOGS_API_PATH } from "@vite-plugin-opencode-assistant/shared";
|
|
9
10
|
export * from "./types.mjs";
|
|
10
|
-
function setupMiddlewares(server, ctx) {
|
|
11
|
+
function setupMiddlewares(server, ctx, mcp) {
|
|
11
12
|
setupWidgetEndpoints(server, ctx);
|
|
12
13
|
setupContextEndpoint(server, ctx);
|
|
13
14
|
setupStartEndpoint(server, ctx);
|
|
@@ -15,8 +16,10 @@ function setupMiddlewares(server, ctx) {
|
|
|
15
16
|
setupSessionsEndpoint(server, ctx);
|
|
16
17
|
setupWarmupEndpoint(server, ctx);
|
|
17
18
|
setupLogsEndpoint(server);
|
|
19
|
+
if (mcp) setupMcpEndpoint(server, mcp, () => ctx.getPageContext());
|
|
18
20
|
}
|
|
19
21
|
export {
|
|
20
22
|
LOGS_API_PATH,
|
|
23
|
+
MCP_API_PATH,
|
|
21
24
|
setupMiddlewares
|
|
22
25
|
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 自定义 DevTools 工具定义
|
|
3
|
+
* 所有工具(除 devtools_list_pages)必须传入 pageId 参数,
|
|
4
|
+
* 代理层校验 pageId 是否为项目页面后方可调用 chrome-devtools-mcp。
|
|
5
|
+
*/
|
|
6
|
+
export interface CustomTool {
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: "object";
|
|
11
|
+
properties: Record<string, unknown>;
|
|
12
|
+
required?: string[];
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export declare const CUSTOM_TOOLS: CustomTool[];
|
|
16
|
+
/** 工具名映射(自定义 → chrome-devtools-mcp) */
|
|
17
|
+
export declare const TOOL_MAP: Record<string, string>;
|