mcp-apps-inspector 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # MCP Apps Inspector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 独立的 MCP Server 与 MCP Apps 本地调试工具。内外使用同一个公开 npm 包 `mcp-apps-inspector`,不依赖应用插件项目或登录状态,版本独立于 dbx。
4
+
5
+ ## 基本架构
6
+
7
+ 本包由浏览器调试界面和 Node.js 本地服务组成,不依赖 CLI,也不读取应用插件项目。命令行入口通过 `startInspector` 启动服务并传入连接地址、请求头;浏览器通过 `/__inspector/config` 获取启动配置。
8
+
9
+ | 文件或目录 | 职责 |
10
+ | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
11
+ | `src/server/` | 提供静态页面、启动配置和 MCP 请求代理,管理独立的沙箱服务及浏览器窗口。 |
12
+ | `src/web/core/session.ts` | 管理 MCP 连接和工具、资源列表,执行调用与读取,记录 HTTP / JSON-RPC 通信。 |
13
+ | `src/web/components/` | 左侧画布、中间 Tools / Resources、右侧请求记录和底部 Console 抽屉;工具统一在 Tools 中选择和运行。 |
14
+ | `src/web/components/AppFrame.tsx`、`public/sandbox-proxy.html` | 通过双层 iframe 预览工具的 UI,以 AppBridge 传递初始化、工具输入、调用结果和尺寸消息。 |
15
+ | `src/web/core/console.ts` | 采集宿主页面和应用 iframe 的日志、运行错误及资源加载错误,供 Console 展示。 |
16
+
17
+ MCP 请求由浏览器经同源 `/__mcp_proxy` 转发到目标服务,使用 Streamable HTTP。请求记录展示 MCP 通信,不包含预览页面内的全部静态资源请求。本地服务仅监听 `127.0.0.1`,校验 Host,且不开放跨域访问。
18
+
19
+ UI 预览的消息链路为:宿主页面 ⇄ 独立端口的沙箱代理 ⇄ 应用 iframe。外层代理位于独立源,内层 iframe 使用 `sandbox="allow-scripts allow-forms"` 和应用声明的 CSP,不能添加 `allow-same-origin`。宿主读取工具声明的 UI 资源,再经代理加载页面。
20
+
21
+ ## 使用
22
+
23
+ ```sh
24
+ npx --yes --prefer-online --registry=https://registry.npmjs.org mcp-apps-inspector@latest --mcp-server
25
+ npx --yes --prefer-online --registry=https://registry.npmjs.org mcp-apps-inspector@latest --mcp-server http://localhost:8080/api/mcp --no-open
26
+ ```
27
+
28
+ `--mcp-server` 可不带地址;`-H` / `--header "Key: Value"` 可重复传入。`--port` 指定端口,默认从 6274 自动寻找空闲端口;显式指定的端口被占用时报错。默认打开 Chrome / Edge 应用窗口,`--no-open` 仅启动服务。按 Ctrl+C 退出并关闭本地服务。请求头不会写入终端日志。
29
+
30
+ `dbx inspect --mcp-server [endpoint]` 保持原有用法,由 dbx 通过 npx 启动本包。每次启动检查 `latest`,下载复用 npm 缓存,更新 Inspector 无需更新 dbx。需要能够访问公开 npm registry。
31
+
32
+ 也可在 Node.js 中调用:
33
+
34
+ ```ts
35
+ import { startInspector } from 'mcp-apps-inspector';
36
+
37
+ const inspector = await startInspector({ endpoint: 'http://localhost:8088/mcp', headers: {} });
38
+ console.log(inspector.url);
39
+ await inspector.close();
40
+ ```
41
+
42
+ ## 本地开发
43
+
44
+ 需要 Node.js >=22.13.0 与 Corepack。在仓库根目录执行 `corepack pnpm install` 安装依赖后运行:
45
+
46
+ ```bash
47
+ MCP_ENDPOINT=http://localhost:8080/api/mcp corepack pnpm dev
48
+ corepack pnpm typecheck
49
+ corepack pnpm lint
50
+ corepack pnpm build
51
+ ```
52
+
53
+ 页面由 Rsbuild 构建到 `dist/web`,本地服务由 Rslib 构建到 `dist/index.js`;两端只共享 `src/config.ts`。
54
+
55
+ 开发页面默认位于 `http://localhost:6274/`,可通过 `PORT` 修改端口。沙箱服务默认使用 6275,端口占用时自动选择空闲端口。
56
+ 修改服务端、`rsbuild.config.ts` 或 `public/sandbox-proxy.html` 后需要重启开发服务;通过 CLI 运行时需先重新构建。UI 改动需在浏览器中验证。
57
+
58
+ ## 独立发布
59
+
60
+ 本仓库独立维护 `package.json` 版本与 `pnpm-lock.yaml`。只发布 `bin/`、构建后的 `dist/` 和本文档,构建工具不进入运行时依赖。
61
+
62
+ 版本修改合入 `main` 后,运行本仓库的 `Release Inspector` 手动流水线。需在仓库 CI 中配置有本包发布权限的 `NPM_TOKEN`,流水线使用锁文件安装、检查、构建并发布公开 npm 包。稳定版本更新 `latest`;预发布版本使用 `next`,不会被 dbx 自动采用。已发布版本不可覆盖,修改后应递增版本。
63
+
64
+ 本地已登录有权限的 npm 账号时,也可运行 `corepack pnpm publish --access public --registry=https://registry.npmjs.org --tag latest`;发布前会执行类型检查和构建。预发布请使用 `--tag next`。
package/bin/run.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/cli.js';
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cli.d.ts.map
package/dist/cli.js ADDED
@@ -0,0 +1,85 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { Command } from "commander";
3
+ import { log } from "@clack/prompts";
4
+ import { startInspector } from "./index.js";
5
+ const cli_log = process.stdin.isTTY && process.stdout.isTTY ? log : {
6
+ info: (message)=>console.log(stripVTControlCharacters(message)),
7
+ success: (message)=>console.log(stripVTControlCharacters(message)),
8
+ warn: (message)=>console.error(stripVTControlCharacters(message))
9
+ };
10
+ function parseEndpoint(value) {
11
+ let url;
12
+ try {
13
+ url = new URL(value);
14
+ } catch {
15
+ throw new Error(`MCP Server 地址无效:${value},仅支持 http:// 或 https://`);
16
+ }
17
+ if ('http:' !== url.protocol && 'https:' !== url.protocol) throw new Error(`MCP Server 地址无效:${value},仅支持 http:// 或 https://`);
18
+ return value;
19
+ }
20
+ function parseHeaders(values) {
21
+ const headers = {};
22
+ for (const value of values){
23
+ const separator = value.indexOf(':');
24
+ const key = separator > 0 ? value.slice(0, separator).trim() : '';
25
+ if (!key) throw new Error(`请求头格式应为 "Key: Value":${value}`);
26
+ headers[key] = value.slice(separator + 1).trim();
27
+ }
28
+ return headers;
29
+ }
30
+ function parsePort(value) {
31
+ if (void 0 === value) return;
32
+ const port = Number(value);
33
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`端口无效:${value},应为 1-65535 的整数`);
34
+ return port;
35
+ }
36
+ async function runInspect(options) {
37
+ if (void 0 === options.mcpServer) throw new Error('请指定调试对象,例如 mcp-apps-inspector --mcp-server [endpoint]');
38
+ const endpoint = 'string' == typeof options.mcpServer ? parseEndpoint(options.mcpServer) : void 0;
39
+ const headers = parseHeaders(options.header ?? []);
40
+ const port = parsePort(options.port);
41
+ const controller = new AbortController();
42
+ const completion = Promise.withResolvers();
43
+ const stop = (exitCode)=>{
44
+ process.exitCode = exitCode;
45
+ controller.abort();
46
+ completion.resolve();
47
+ };
48
+ const onSigint = ()=>stop(130);
49
+ const onSigterm = ()=>stop(143);
50
+ process.on('SIGINT', onSigint);
51
+ process.on('SIGTERM', onSigterm);
52
+ try {
53
+ const inspector = await startInspector({
54
+ endpoint,
55
+ headers,
56
+ port,
57
+ open: options.open,
58
+ signal: controller.signal,
59
+ log: cli_log
60
+ });
61
+ try {
62
+ cli_log.success(`MCP 调试界面已启动:${inspector.url}`);
63
+ if (endpoint) cli_log.info(`正在连接 ${endpoint}`);
64
+ cli_log.info('按 Ctrl+C 退出');
65
+ await completion.promise;
66
+ } finally{
67
+ await inspector.close();
68
+ }
69
+ } catch (error) {
70
+ if (!controller.signal.aborted) throw error;
71
+ } finally{
72
+ process.off('SIGINT', onSigint);
73
+ process.off('SIGTERM', onSigterm);
74
+ }
75
+ }
76
+ const program = new Command().name('mcp-apps-inspector').description('启动本地调试界面,调试 MCP Server 和 MCP Apps').option('--mcp-server [endpoint]', '调试 MCP Server,可带地址').option('-H, --header <header>', '请求头,格式为 "Key: Value",可写多次', (value, previous = [])=>[
77
+ ...previous,
78
+ value
79
+ ]).option('--port <port>', '调试界面端口,默认 6274;被占用时自动顺延').option('--no-open', '只启动服务,不打开窗口').action(runInspect);
80
+ try {
81
+ await program.parseAsync();
82
+ } catch (error) {
83
+ console.error(error instanceof Error ? error.message : String(error));
84
+ process.exitCode = 1;
85
+ }
@@ -0,0 +1,10 @@
1
+ /** Served by the host so the page can pick up `dbx inspect --mcp-server <endpoint>` arguments. */
2
+ export declare const INSPECTOR_CONFIG_PATH = "/__inspector/config";
3
+ export interface InspectorConfig {
4
+ /** Endpoint passed on the command line; null lets the page use its saved connection. */
5
+ endpoint: string | null;
6
+ headers: Record<string, string>;
7
+ /** Trusted sandbox proxy on a separate loopback origin. */
8
+ sandboxUrl: string;
9
+ }
10
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,6 @@
1
+ export declare const HOST = "127.0.0.1";
2
+ export declare const DEFAULT_PORT = 6274;
3
+ /** Ports tried after the default one when it is busy and no port was requested. */
4
+ export declare const PORT_ATTEMPTS = 20;
5
+ export declare const BROWSER_PROFILE_DIRECTORY: string;
6
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { startInspector } from './server/start.js';
2
+ export type { InspectorHandle, InspectorLogger, InspectorOptions } from './types.js';
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,333 @@
1
+ import { createReadStream, existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import node_http, { createServer } from "node:http";
3
+ import { fileURLToPath } from "node:url";
4
+ import open_0 from "open";
5
+ import { homedir } from "node:os";
6
+ import node_path, { join } from "node:path";
7
+ import { Readable } from "node:stream";
8
+ import { stat } from "node:fs/promises";
9
+ import { spawn } from "node:child_process";
10
+ const INSPECTOR_CONFIG_PATH = '/__inspector/config';
11
+ const HOST = '127.0.0.1';
12
+ const BROWSER_PROFILE_DIRECTORY = join(homedir(), '.dbx', 'mcp-inspector', 'browser-profile');
13
+ function listen(server, port) {
14
+ return new Promise((resolve, reject)=>{
15
+ server.once('error', reject);
16
+ server.listen(port, HOST, ()=>{
17
+ server.off('error', reject);
18
+ resolve(server.address().port);
19
+ });
20
+ });
21
+ }
22
+ function closeServer(server) {
23
+ return new Promise((resolve)=>{
24
+ server.close(()=>resolve());
25
+ server.closeAllConnections();
26
+ });
27
+ }
28
+ const MCP_PROXY_PATH = '/__mcp_proxy';
29
+ const MCP_TARGET_HEADER = 'x-mcp-target';
30
+ const DROP_REQUEST_HEADERS = new Set([
31
+ 'host',
32
+ 'origin',
33
+ 'referer',
34
+ 'connection',
35
+ 'content-length',
36
+ 'accept-encoding',
37
+ 'cookie',
38
+ MCP_TARGET_HEADER
39
+ ]);
40
+ const DROP_RESPONSE_HEADERS = new Set([
41
+ 'content-encoding',
42
+ 'content-length',
43
+ 'transfer-encoding',
44
+ 'connection',
45
+ 'keep-alive'
46
+ ]);
47
+ function readBody(req) {
48
+ return new Promise((resolve, reject)=>{
49
+ const chunks = [];
50
+ req.on('data', (c)=>chunks.push(c));
51
+ req.on('end', ()=>resolve(Buffer.concat(chunks)));
52
+ req.on('error', reject);
53
+ });
54
+ }
55
+ function fail(res, status, message) {
56
+ res.statusCode = status;
57
+ res.setHeader('content-type', 'application/json');
58
+ res.end(JSON.stringify({
59
+ error: message
60
+ }));
61
+ }
62
+ async function mcpProxyMiddleware(req, res, next) {
63
+ if (!req.url?.startsWith(MCP_PROXY_PATH)) return next();
64
+ const rawTarget = req.headers[MCP_TARGET_HEADER];
65
+ const target = Array.isArray(rawTarget) ? rawTarget[0] : rawTarget;
66
+ let url;
67
+ try {
68
+ url = new URL(target ?? '');
69
+ } catch {
70
+ return fail(res, 400, `Invalid ${MCP_TARGET_HEADER} header`);
71
+ }
72
+ if ('http:' !== url.protocol && 'https:' !== url.protocol) return fail(res, 400, 'Only http(s) MCP endpoints can be proxied');
73
+ const headers = new Headers();
74
+ for (const [key, value] of Object.entries(req.headers))if (!(void 0 === value || DROP_REQUEST_HEADERS.has(key))) headers.set(key, Array.isArray(value) ? value.join(', ') : value);
75
+ const method = req.method ?? 'GET';
76
+ const body = 'GET' === method || 'HEAD' === method ? void 0 : await readBody(req);
77
+ const abort = new AbortController();
78
+ res.on('close', ()=>abort.abort());
79
+ let upstream;
80
+ try {
81
+ upstream = await fetch(url, {
82
+ method,
83
+ headers,
84
+ body: body && body.length > 0 ? new Uint8Array(body) : void 0,
85
+ signal: abort.signal,
86
+ redirect: 'manual'
87
+ });
88
+ } catch (err) {
89
+ if (abort.signal.aborted) return;
90
+ const reason = err instanceof Error ? err.cause ?? err : err;
91
+ return fail(res, 502, `Cannot reach ${url.href}: ${String(reason)}`);
92
+ }
93
+ res.statusCode = upstream.status;
94
+ res.statusMessage = upstream.statusText;
95
+ upstream.headers.forEach((value, key)=>{
96
+ if (!DROP_RESPONSE_HEADERS.has(key)) res.setHeader(key, value);
97
+ });
98
+ res.flushHeaders();
99
+ if (!upstream.body) return res.end();
100
+ Readable.fromWeb(upstream.body).on('error', ()=>res.destroy()).pipe(res);
101
+ }
102
+ const DEFAULT_SANDBOX_PORT = 6275;
103
+ const EMBEDDER_ORIGINS_PLACEHOLDER = '/*INSPECTOR_EMBEDDER_ORIGINS*/ null';
104
+ function inspectorOrigins(port) {
105
+ return [
106
+ `http://${HOST}:${port}`,
107
+ `http://localhost:${port}`
108
+ ];
109
+ }
110
+ async function startSandboxServer({ htmlPath, allowedOrigins, port = DEFAULT_SANDBOX_PORT }) {
111
+ if (0 === allowedOrigins.length || allowedOrigins.some((origin)=>!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(origin))) throw new Error('Sandbox requires explicit loopback Inspector origins');
112
+ const template = readFileSync(htmlPath, 'utf8');
113
+ if (!template.includes(EMBEDDER_ORIGINS_PLACEHOLDER)) throw new Error('Sandbox proxy template is missing its embedder origins marker');
114
+ const html = template.replace(EMBEDDER_ORIGINS_PLACEHOLDER, ()=>JSON.stringify(allowedOrigins).replace(/</g, '\\u003c'));
115
+ let boundPort = 0;
116
+ const server = createServer((req, res)=>{
117
+ if (!inspectorOrigins(boundPort).some((origin)=>new URL(origin).host === req.headers.host)) {
118
+ res.writeHead(403);
119
+ res.end('Forbidden');
120
+ return;
121
+ }
122
+ if ('GET' !== req.method || '/sandbox' !== req.url && '/sandbox/' !== req.url) {
123
+ res.writeHead(404);
124
+ res.end('Not Found');
125
+ return;
126
+ }
127
+ res.writeHead(200, {
128
+ 'content-type': 'text/html; charset=utf-8',
129
+ 'cache-control': 'no-store',
130
+ 'x-content-type-options': 'nosniff',
131
+ 'content-security-policy': `frame-ancestors ${allowedOrigins.join(' ')}`
132
+ });
133
+ res.end(html);
134
+ });
135
+ try {
136
+ const conflictsWithInspector = allowedOrigins.some((origin)=>new URL(origin).port === String(port));
137
+ boundPort = await listen(server, conflictsWithInspector ? 0 : port);
138
+ } catch (error) {
139
+ if ('EADDRINUSE' !== error.code) throw error;
140
+ boundPort = await listen(server, 0);
141
+ }
142
+ let closing;
143
+ return {
144
+ url: `http://${HOST}:${boundPort}/sandbox`,
145
+ close: ()=>closing ??= closeServer(server)
146
+ };
147
+ }
148
+ const MIME_TYPES = {
149
+ '.html': 'text/html; charset=utf-8',
150
+ '.js': "text/javascript; charset=utf-8",
151
+ '.css': 'text/css; charset=utf-8',
152
+ '.json': 'application/json',
153
+ '.svg': 'image/svg+xml',
154
+ '.png': 'image/png',
155
+ '.ico': 'image/x-icon',
156
+ '.woff2': 'font/woff2',
157
+ '.txt': 'text/plain; charset=utf-8'
158
+ };
159
+ async function isFile(file) {
160
+ try {
161
+ return (await stat(file)).isFile();
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+ function createStaticMiddleware(root) {
167
+ return async (req, res, next)=>{
168
+ if ('GET' !== req.method && 'HEAD' !== req.method) return next();
169
+ let pathname;
170
+ try {
171
+ pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname);
172
+ } catch {
173
+ return next();
174
+ }
175
+ let file = node_path.join(root, pathname);
176
+ if (file !== root && !file.startsWith(`${root}${node_path.sep}`)) return next();
177
+ if (!await isFile(file)) {
178
+ if (node_path.extname(pathname)) return next();
179
+ file = node_path.join(root, 'index.html');
180
+ }
181
+ res.statusCode = 200;
182
+ res.setHeader('content-type', MIME_TYPES[node_path.extname(file)] ?? 'application/octet-stream');
183
+ if ('HEAD' === req.method) return res.end();
184
+ createReadStream(file).on('error', ()=>res.destroy()).pipe(res);
185
+ };
186
+ }
187
+ const MAC_BROWSERS = [
188
+ 'Google Chrome',
189
+ 'Microsoft Edge',
190
+ 'Chromium',
191
+ 'Brave Browser'
192
+ ];
193
+ const LINUX_BROWSERS = [
194
+ 'google-chrome',
195
+ 'google-chrome-stable',
196
+ 'chromium',
197
+ 'chromium-browser',
198
+ 'microsoft-edge'
199
+ ];
200
+ const WIN_BROWSERS = [
201
+ `${process.env.ProgramFiles}\\Google\\Chrome\\Application\\chrome.exe`,
202
+ `${process.env['ProgramFiles(x86)']}\\Microsoft\\Edge\\Application\\msedge.exe`
203
+ ];
204
+ function launch(command, args) {
205
+ return new Promise((resolve)=>{
206
+ const child = spawn(command, args, {
207
+ stdio: 'ignore',
208
+ detached: true
209
+ });
210
+ child.on('error', ()=>resolve(false));
211
+ child.on('spawn', ()=>{
212
+ child.unref();
213
+ resolve(true);
214
+ });
215
+ });
216
+ }
217
+ async function openAppWindow(url) {
218
+ mkdirSync(BROWSER_PROFILE_DIRECTORY, {
219
+ recursive: true
220
+ });
221
+ const args = [
222
+ `--app=${url}`,
223
+ `--user-data-dir=${BROWSER_PROFILE_DIRECTORY}`,
224
+ '--window-size=1440,900',
225
+ '--no-first-run',
226
+ '--no-default-browser-check'
227
+ ];
228
+ if ('darwin' === process.platform) {
229
+ for (const name of MAC_BROWSERS)if (existsSync(`/Applications/${name}.app`)) return launch('open', [
230
+ '-na',
231
+ name,
232
+ '--args',
233
+ ...args
234
+ ]);
235
+ } else if ('win32' === process.platform) {
236
+ for (const exe of WIN_BROWSERS)if (existsSync(exe)) return launch(exe, args);
237
+ } else for (const bin of LINUX_BROWSERS)if (await launch(bin, args)) return true;
238
+ return false;
239
+ }
240
+ const WEB_ROOT = fileURLToPath(new URL('./web', import.meta.url));
241
+ async function listenOnFreePort(server, port) {
242
+ const first = port ?? 6274;
243
+ const last = port ?? 6294;
244
+ for(let candidate = first; candidate <= last; candidate++)try {
245
+ return await listen(server, candidate);
246
+ } catch (error) {
247
+ if ('EADDRINUSE' !== error.code) throw error;
248
+ }
249
+ throw new Error(void 0 === port ? `端口 ${first}-${last} 都已被占用,请用 --port 指定其他端口` : `端口 ${port} 已被占用,请换一个端口`);
250
+ }
251
+ async function startInspector(options = {}) {
252
+ const { endpoint, headers = {}, port, open: shouldOpen = true, signal, log } = options;
253
+ signal?.throwIfAborted();
254
+ if (!existsSync(WEB_ROOT)) throw new Error(`MCP 调试界面资源缺失:${WEB_ROOT}`);
255
+ let config;
256
+ const serveStatic = createStaticMiddleware(WEB_ROOT);
257
+ const notFound = (res)=>{
258
+ res.statusCode = 404;
259
+ res.end();
260
+ };
261
+ let listening = 0;
262
+ const server = node_http.createServer((req, res)=>{
263
+ const { host } = req.headers;
264
+ if (host !== `${HOST}:${listening}` && host !== `localhost:${listening}`) {
265
+ res.statusCode = 403;
266
+ res.end('Forbidden');
267
+ return;
268
+ }
269
+ if ('GET' === req.method && req.url?.split('?')[0] === INSPECTOR_CONFIG_PATH) {
270
+ if (!config) {
271
+ res.statusCode = 503;
272
+ res.end('Sandbox is starting');
273
+ return;
274
+ }
275
+ res.setHeader('content-type', 'application/json');
276
+ res.setHeader('cache-control', 'no-store');
277
+ res.end(config);
278
+ return;
279
+ }
280
+ mcpProxyMiddleware(req, res, ()=>serveStatic(req, res, ()=>notFound(res))).catch(()=>{
281
+ if (res.headersSent) res.destroy();
282
+ else {
283
+ res.statusCode = 500;
284
+ res.end();
285
+ }
286
+ });
287
+ });
288
+ listening = await listenOnFreePort(server, port);
289
+ let sandbox;
290
+ try {
291
+ sandbox = await startSandboxServer({
292
+ htmlPath: fileURLToPath(new URL('./web/sandbox-proxy.html', import.meta.url)),
293
+ allowedOrigins: inspectorOrigins(listening)
294
+ });
295
+ config = JSON.stringify({
296
+ endpoint: endpoint ?? null,
297
+ headers,
298
+ sandboxUrl: sandbox.url
299
+ });
300
+ } catch (error) {
301
+ await closeServer(server);
302
+ throw error;
303
+ }
304
+ let closing;
305
+ const close = ()=>closing ??= Promise.all([
306
+ closeServer(server),
307
+ sandbox.close()
308
+ ]).then(()=>{});
309
+ if (signal?.aborted) {
310
+ await close();
311
+ signal.throwIfAborted();
312
+ }
313
+ signal?.addEventListener('abort', ()=>void close(), {
314
+ once: true
315
+ });
316
+ const url = `http://${HOST}:${listening}/`;
317
+ let appWindow = false;
318
+ if (shouldOpen) try {
319
+ appWindow = await openAppWindow(url);
320
+ if (!appWindow) {
321
+ await open_0(url);
322
+ log?.warn('未找到 Chrome / Edge,已用默认浏览器打开调试界面');
323
+ }
324
+ } catch (error) {
325
+ log?.warn(`未能打开调试界面,请手动访问 ${url}:${error instanceof Error ? error.message : String(error)}`);
326
+ }
327
+ return {
328
+ url,
329
+ appWindow,
330
+ close
331
+ };
332
+ }
333
+ export { startInspector };
@@ -0,0 +1,5 @@
1
+ import type { Server } from 'node:http';
2
+ export declare function listen(server: Server, port: number): Promise<number>;
3
+ /** Close idle sockets and long-lived streams as well as the listener. */
4
+ export declare function closeServer(server: Server): Promise<void>;
5
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ export declare const MCP_PROXY_PATH = "/__mcp_proxy";
3
+ export declare const MCP_TARGET_HEADER = "x-mcp-target";
4
+ /**
5
+ * Relays one MCP HTTP request (Streamable HTTP POST/GET/DELETE or legacy SSE)
6
+ * to the URL named in the `x-mcp-target` header, streaming the response back
7
+ * so long-lived SSE streams keep working.
8
+ */
9
+ export declare function mcpProxyMiddleware(req: IncomingMessage, res: ServerResponse, next: () => void): Promise<void | ServerResponse<IncomingMessage>>;
10
+ //# sourceMappingURL=mcp-proxy.d.ts.map
@@ -0,0 +1,11 @@
1
+ export declare function inspectorOrigins(port: number): string[];
2
+ /** A separate origin serving only the trusted MCP Apps sandbox proxy. */
3
+ export declare function startSandboxServer({ htmlPath, allowedOrigins, port }: {
4
+ htmlPath: string;
5
+ allowedOrigins: string[];
6
+ port?: number;
7
+ }): Promise<{
8
+ url: string;
9
+ close: () => Promise<void>;
10
+ }>;
11
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1,4 @@
1
+ import type { InspectorHandle, InspectorOptions } from '../types.js';
2
+ /** Starts the MCP inspector page on loopback and opens it. */
3
+ export declare function startInspector(options?: InspectorOptions): Promise<InspectorHandle>;
4
+ //# sourceMappingURL=start.d.ts.map
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** Serves the built page from `root`; unknown extensionless paths fall back to index.html. */
3
+ export declare function createStaticMiddleware(root: string): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void | ServerResponse<IncomingMessage>>;
4
+ //# sourceMappingURL=static.d.ts.map
@@ -0,0 +1,3 @@
1
+ /** Resolves false when no Chromium-based browser could be launched. */
2
+ export declare function openAppWindow(url: string): Promise<boolean>;
3
+ //# sourceMappingURL=window.d.ts.map
@@ -0,0 +1,25 @@
1
+ export interface InspectorLogger {
2
+ info(message: string): void;
3
+ warn(message: string): void;
4
+ }
5
+ export interface InspectorOptions {
6
+ /** MCP Server endpoint; when omitted the page reuses its saved connection. */
7
+ endpoint?: string;
8
+ /** Headers sent with every MCP request. */
9
+ headers?: Record<string, string>;
10
+ /** Port to listen on; a busy port is an error. Defaults to the first free port from 6274. */
11
+ port?: number;
12
+ /** Opens the inspector window; defaults to true. */
13
+ open?: boolean;
14
+ /** Closes the server when aborted. */
15
+ signal?: AbortSignal;
16
+ log?: InspectorLogger;
17
+ }
18
+ export interface InspectorHandle {
19
+ /** For example `http://127.0.0.1:6274/`. */
20
+ url: string;
21
+ /** Whether a chromeless app window was opened; false when a normal browser tab was used or nothing was opened. */
22
+ appWindow: boolean;
23
+ close(): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ <!DOCTYPE html><html><head><title>MCP Apps Inspector</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><script defer src="/static/js/lib-react.00514652bf.js"></script><script defer src="/static/js/155.747f5232dc.js"></script><script defer src="/static/js/index.c1186260b9.js"></script><link href="/static/css/index.b3102f16b9.css" rel="stylesheet"></head><body><div id="root"></div></body></html>