@vultro/cli 0.0.0-stage → 0.0.2
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 +142 -2
- package/dist/_virtual/_vite/preload-helper.js +102 -0
- package/dist/args.d.ts +75 -0
- package/dist/args.js +169 -0
- package/dist/check.d.ts +44 -0
- package/dist/check.js +295 -0
- package/dist/codegen-content.d.ts +77 -0
- package/dist/codegen-content.js +594 -0
- package/dist/codegen.d.ts +37 -0
- package/dist/codegen.js +115 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +169 -0
- package/dist/mcp.d.ts +91 -0
- package/dist/mcp.js +440 -0
- package/dist/project.d.ts +172 -0
- package/dist/project.js +597 -0
- package/dist/run.d.ts +37 -0
- package/dist/run.js +103 -0
- package/dist/typecheck.d.ts +36 -0
- package/dist/typecheck.js +85 -0
- package/package.json +29 -4
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
// src/mcp.ts
|
|
7
|
+
/**
|
|
8
|
+
* ============================================================================
|
|
9
|
+
* `vultro mcp`:把后端作为 MCP server 暴露在 stdio 上
|
|
10
|
+
* ============================================================================
|
|
11
|
+
*
|
|
12
|
+
* 与 `concave mcp` 的定位一致:一个常驻的「翻译层」,把 agent 工具调用翻译成
|
|
13
|
+
* 对**正在运行的 dev server** 的 HTTP 调用。它不启动 dev server、不连数据库,
|
|
14
|
+
* 只通过 `@vultro/vite-plugin` 写出的 `.vultro/agent/status.json` 发现后端。
|
|
15
|
+
*
|
|
16
|
+
* 协议层使用官方 `@modelcontextprotocol/sdk`:`McpServer` + `StdioServerTransport`
|
|
17
|
+
* 负责协议握手、版本协商、`tools/list` / `tools/call` 分发与 `ping`,这里只
|
|
18
|
+
* 注册工具和实现策略。
|
|
19
|
+
*
|
|
20
|
+
* 安全模型(与 concave mcp 对齐):
|
|
21
|
+
* - 默认只读:`run_query` 始终可用;`run_mutation` / `run_action` 需要
|
|
22
|
+
* `--writes` 或 `VULTRO_MCP_ALLOW_WRITES=1`;
|
|
23
|
+
* - internal 函数默认拒绝(`--allow-internal` 解锁;远程目标还需要 admin key);
|
|
24
|
+
* - `--allow "messages:*"` 白名单(glob / 前缀);
|
|
25
|
+
* - 调用凭据取 `VULTRO_ADMIN_TOKEN`,以 `Authorization: Convex <key>` 发送;
|
|
26
|
+
* 本机 dev server 无需凭据(平台层按真实连接来源放行)。
|
|
27
|
+
*/
|
|
28
|
+
/** 状态文件相对项目根的位置(与 `@vultro/vite-plugin` 的写入方一致)。 */
|
|
29
|
+
var AGENT_STATUS_FILE = join(".vultro", "agent", "status.json");
|
|
30
|
+
/** 函数清单缓存 TTL;dev server 的函数集在 codegen 后才会变化。 */
|
|
31
|
+
var SPEC_TTL_MS = 3e4;
|
|
32
|
+
/** 从 CliOptions 提取 MCP 选项。 */
|
|
33
|
+
function mcpOptionsFromCli(options) {
|
|
34
|
+
return {
|
|
35
|
+
port: options.mcpPort,
|
|
36
|
+
url: options.mcpUrl,
|
|
37
|
+
writes: options.mcpWrites === true || {}.VULTRO_MCP_ALLOW_WRITES === "1",
|
|
38
|
+
allowInternal: options.mcpAllowInternal === true,
|
|
39
|
+
allow: options.mcpAllow ?? [],
|
|
40
|
+
cwd: resolve(options.dir ?? process.cwd())
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function createMcpState(options) {
|
|
44
|
+
return {
|
|
45
|
+
options,
|
|
46
|
+
specCache: /* @__PURE__ */ new Map()
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 解析后端地址;解析不到时返回 undefined 并给出已尝试的来源,
|
|
51
|
+
* 让 `status` 工具能把原因告诉 agent,而不是静默打错端口。
|
|
52
|
+
*/
|
|
53
|
+
function resolveBackendUrl(options) {
|
|
54
|
+
if (options.url) return {
|
|
55
|
+
url: trimSlash(options.url),
|
|
56
|
+
source: "--url"
|
|
57
|
+
};
|
|
58
|
+
if (options.port) return {
|
|
59
|
+
url: `http://localhost:${options.port}`,
|
|
60
|
+
source: "--port"
|
|
61
|
+
};
|
|
62
|
+
const status = findActiveAgentStatus(options.cwd);
|
|
63
|
+
if (status?.backendUrl) return {
|
|
64
|
+
url: trimSlash(status.backendUrl),
|
|
65
|
+
source: AGENT_STATUS_FILE
|
|
66
|
+
};
|
|
67
|
+
const env = {}.VULTRO_URL;
|
|
68
|
+
if (env) return {
|
|
69
|
+
url: trimSlash(env),
|
|
70
|
+
source: "VULTRO_URL"
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** 从起始目录向上查找「活跃」的状态文件(ready 且未 stopped 且 pid 存活)。 */
|
|
74
|
+
function findActiveAgentStatus(cwd) {
|
|
75
|
+
let current = resolve(cwd);
|
|
76
|
+
while (true) {
|
|
77
|
+
const status = readActiveStatus(current);
|
|
78
|
+
if (status) return status;
|
|
79
|
+
const parent = dirname(current);
|
|
80
|
+
if (parent === current) return void 0;
|
|
81
|
+
current = parent;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function readActiveStatus(projectRoot) {
|
|
85
|
+
const filePath = join(projectRoot, AGENT_STATUS_FILE);
|
|
86
|
+
if (!existsSync(filePath)) return void 0;
|
|
87
|
+
let record;
|
|
88
|
+
try {
|
|
89
|
+
const parsed = JSON.parse(readFileSync(filePath, "utf8"));
|
|
90
|
+
if (parsed.ready !== true || parsed.stopped === true || typeof parsed.backendUrl !== "string" || parsed.backendUrl.length === 0) return;
|
|
91
|
+
if (typeof parsed.pid === "number" && !isProcessAlive(parsed.pid)) return;
|
|
92
|
+
record = {
|
|
93
|
+
backendUrl: parsed.backendUrl,
|
|
94
|
+
pid: parsed.pid
|
|
95
|
+
};
|
|
96
|
+
} catch {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
return record;
|
|
100
|
+
}
|
|
101
|
+
/** `process.kill(pid, 0)` 只做存活探测;EPERM 视为存活(无权限但存在)。 */
|
|
102
|
+
function isProcessAlive(pid) {
|
|
103
|
+
try {
|
|
104
|
+
process.kill(pid, 0);
|
|
105
|
+
return true;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
return error.code === "EPERM";
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function trimSlash(url) {
|
|
111
|
+
return url.replace(/\/+$/, "");
|
|
112
|
+
}
|
|
113
|
+
/** 调用后端时携带的凭据头。 */
|
|
114
|
+
function authHeaders() {
|
|
115
|
+
const token = {}.VULTRO_ADMIN_TOKEN;
|
|
116
|
+
return token ? { Authorization: `Convex ${token}` } : {};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* 拉取(带缓存)后端函数清单。
|
|
120
|
+
*
|
|
121
|
+
* `listForAllComponents` 返回 `[[component | null, [file, {functions}]], ...]`:
|
|
122
|
+
* 根组件的 key 是 null,子组件的 key 是组件路径。
|
|
123
|
+
*/
|
|
124
|
+
async function loadFunctions(state, backendUrl) {
|
|
125
|
+
const cached = state.specCache.get("");
|
|
126
|
+
if (cached && Date.now() - cached.fetchedAt < SPEC_TTL_MS) return cached.functions;
|
|
127
|
+
const raw = await postQuery(backendUrl, "_system/frontend/modules:listForAllComponents", {});
|
|
128
|
+
const functions = [];
|
|
129
|
+
for (const [component, list] of raw ?? []) {
|
|
130
|
+
const entries = Array.isArray(list) ? list : [];
|
|
131
|
+
for (const [file, entry] of entries) {
|
|
132
|
+
const module = String(file).replace(/\.js$/, "");
|
|
133
|
+
for (const fn of entry.functions) {
|
|
134
|
+
const callPath = `${module}:${fn.name}`;
|
|
135
|
+
functions.push({
|
|
136
|
+
path: component ? `${component}:${callPath}` : callPath,
|
|
137
|
+
callPath,
|
|
138
|
+
componentPath: component ?? void 0,
|
|
139
|
+
type: fn.udfType.toLowerCase(),
|
|
140
|
+
visibility: fn.visibility.kind === "public" ? "public" : "internal"
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
state.specCache.set("", {
|
|
146
|
+
fetchedAt: Date.now(),
|
|
147
|
+
functions
|
|
148
|
+
});
|
|
149
|
+
return functions;
|
|
150
|
+
}
|
|
151
|
+
/** MCP 策略错误;映射为 `isError: true` 的工具结果。 */
|
|
152
|
+
var McpPolicyError = class extends Error {};
|
|
153
|
+
/** 校验目标函数满足 MCP 策略(存在 / 类型 / internal / 白名单)。 */
|
|
154
|
+
async function resolveFunction(state, backendUrl, name, kind) {
|
|
155
|
+
const functions = await loadFunctions(state, backendUrl);
|
|
156
|
+
const target = name.trim();
|
|
157
|
+
const spec = functions.find((fn) => fn.path === target);
|
|
158
|
+
if (!spec) {
|
|
159
|
+
const suggestions = functions.filter((fn) => fn.type === kind).slice(0, 8).map((fn) => fn.path);
|
|
160
|
+
throw new McpPolicyError(`未知函数 "${name}"。先用 function_spec 工具列出可调用函数。${suggestions.length > 0 ? ` 可用的 ${kind} 函数:${suggestions.join(", ")}。` : ""}`);
|
|
161
|
+
}
|
|
162
|
+
if (spec.type !== kind) {
|
|
163
|
+
const toolFor = {
|
|
164
|
+
query: "run_query",
|
|
165
|
+
mutation: "run_mutation",
|
|
166
|
+
action: "run_action",
|
|
167
|
+
httpaction: "HTTP 请求"
|
|
168
|
+
};
|
|
169
|
+
const writeNote = (spec.type === "mutation" || spec.type === "action") && !state.options.writes ? ` 写工具未开启;用 \`vultro mcp --writes\` 重启以获得 ${toolFor[spec.type]}。` : "";
|
|
170
|
+
throw new McpPolicyError(`"${name}" 是 ${spec.type},不是 ${kind}。请改用 ${toolFor[spec.type]}。${writeNote}`);
|
|
171
|
+
}
|
|
172
|
+
if (spec.visibility === "internal" && !state.options.allowInternal) throw new McpPolicyError(`"${name}" 是 internal 函数,MCP 默认不暴露。用 \`vultro mcp --allow-internal\` 重启以放开。`);
|
|
173
|
+
if (state.options.allow.length > 0 && !matchesAllowlist(spec.path, state.options.allow)) throw new McpPolicyError(`"${name}" 不在 MCP 白名单内(${state.options.allow.join(", ")})。`);
|
|
174
|
+
return spec;
|
|
175
|
+
}
|
|
176
|
+
/** 白名单匹配:`*` 通配(`messages:*` 匹配 `messages:list`),其余为前缀匹配。 */
|
|
177
|
+
function matchesAllowlist(path, patterns) {
|
|
178
|
+
return patterns.some((pattern) => {
|
|
179
|
+
if (pattern === "*" || pattern === path) return true;
|
|
180
|
+
if (pattern.endsWith(":*")) return path.startsWith(pattern.slice(0, -1));
|
|
181
|
+
if (pattern.endsWith(":")) return path.startsWith(pattern);
|
|
182
|
+
if (!pattern.includes("*")) return path.startsWith(pattern);
|
|
183
|
+
const escaped = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
184
|
+
return new RegExp(`^${escaped}$`).test(path);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/** 执行一个后端函数(`/api/query` / `/api/mutation` / `/api/action`)。 */
|
|
188
|
+
async function executeFunction(backendUrl, kind, path, args, componentPath) {
|
|
189
|
+
const response = await fetch(`${backendUrl}/api/${kind}`, {
|
|
190
|
+
method: "POST",
|
|
191
|
+
headers: {
|
|
192
|
+
"Content-Type": "application/json",
|
|
193
|
+
...authHeaders()
|
|
194
|
+
},
|
|
195
|
+
body: JSON.stringify({
|
|
196
|
+
path,
|
|
197
|
+
args: args ?? {},
|
|
198
|
+
...componentPath ? { componentPath } : {}
|
|
199
|
+
})
|
|
200
|
+
});
|
|
201
|
+
const payload = await response.json().catch(() => void 0);
|
|
202
|
+
if (!response.ok || payload?.status === "error") throw new Error(payload?.errorMessage ?? `后端返回 ${response.status}(${kind} ${path})`);
|
|
203
|
+
return payload?.value;
|
|
204
|
+
}
|
|
205
|
+
/** 调用系统 UDF(`_system/frontend/*`)。 */
|
|
206
|
+
async function postQuery(backendUrl, path, args) {
|
|
207
|
+
const response = await fetch(`${backendUrl}/api/query`, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: {
|
|
210
|
+
"Content-Type": "application/json",
|
|
211
|
+
...authHeaders()
|
|
212
|
+
},
|
|
213
|
+
body: JSON.stringify({
|
|
214
|
+
path,
|
|
215
|
+
args
|
|
216
|
+
})
|
|
217
|
+
});
|
|
218
|
+
const payload = await response.json().catch(() => void 0);
|
|
219
|
+
if (!response.ok || payload?.status === "error") throw new Error(payload?.errorMessage ?? `后端返回 ${response.status}(${path})`);
|
|
220
|
+
return payload?.value;
|
|
221
|
+
}
|
|
222
|
+
/** 工具回调的统一返回体;payload 以 JSON 文本返回,便于 agent 读取。 */
|
|
223
|
+
function ok(payload, isError = false) {
|
|
224
|
+
return {
|
|
225
|
+
content: [{
|
|
226
|
+
type: "text",
|
|
227
|
+
text: JSON.stringify(payload, null, 2)
|
|
228
|
+
}],
|
|
229
|
+
isError
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** 失败结果;统一带 `error` 字段,便于 agent 解析。 */
|
|
233
|
+
function fail(error) {
|
|
234
|
+
return ok({
|
|
235
|
+
ok: false,
|
|
236
|
+
error: error instanceof Error ? error.message : String(error)
|
|
237
|
+
}, true);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* 创建 MCP server 并注册全部工具。
|
|
241
|
+
*
|
|
242
|
+
* 协议细节(握手 / 版本协商 / tools/list / ping)由 SDK 处理;这里只提供
|
|
243
|
+
* 工具回调。策略错误(McpPolicyError)与后端错误都转成 `isError: true` 的
|
|
244
|
+
* 工具结果——MCP 约定工具级失败不抛协议错误,让 agent 能读到错误文本。
|
|
245
|
+
*/
|
|
246
|
+
function createMcpServer(state, version) {
|
|
247
|
+
const server = new McpServer({
|
|
248
|
+
name: "vultro",
|
|
249
|
+
version
|
|
250
|
+
}, { capabilities: { tools: {} } });
|
|
251
|
+
const options = state.options;
|
|
252
|
+
const requireBackendUrl = () => {
|
|
253
|
+
const resolution = resolveBackendUrl(options);
|
|
254
|
+
if (!resolution) throw new McpPolicyError("没有发现运行中的 Vultro dev server。请先 `vultro dev` 启动(状态文件 .vultro/agent/status.json 需要 ready:true),或用 --url / --port 指定后端。");
|
|
255
|
+
return resolution.url;
|
|
256
|
+
};
|
|
257
|
+
server.registerTool("status", { description: "检查 Vultro 后端是否可达并报告地址。其他工具报连接错误时先调用它;后端没起就先 `vultro dev`。" }, async () => {
|
|
258
|
+
try {
|
|
259
|
+
const backendUrl = requireBackendUrl();
|
|
260
|
+
const response = await fetch(`${backendUrl}/health`);
|
|
261
|
+
return ok({
|
|
262
|
+
ok: response.ok,
|
|
263
|
+
url: backendUrl,
|
|
264
|
+
reachable: response.ok
|
|
265
|
+
});
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (!(error instanceof McpPolicyError)) throw error;
|
|
268
|
+
return ok({
|
|
269
|
+
ok: false,
|
|
270
|
+
reachable: false,
|
|
271
|
+
error: error.message,
|
|
272
|
+
hint: "先用 `vultro dev` 启动后端,或给 `vultro mcp` 传 --url / --port。"
|
|
273
|
+
}, true);
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
server.registerTool("run_query", {
|
|
277
|
+
description: `在 dev 部署上执行 Convex query(只读)并返回结果。函数名用 module:export 形式,例如 \`messages:list\`。${options.writes ? "mutation/action 用 run_mutation/run_action。" : "写工具未开启(用 vultro mcp --writes 开启)。"}`,
|
|
278
|
+
inputSchema: {
|
|
279
|
+
name: z.string().describe("函数路径,例如 messages:list"),
|
|
280
|
+
args: z.optional(z.record(z.string(), z.unknown())).describe("函数参数(JSON 对象,默认 {})"),
|
|
281
|
+
componentPath: z.optional(z.string()).describe("组件函数的组件路径(可选)")
|
|
282
|
+
}
|
|
283
|
+
}, async ({ name, args, componentPath }) => {
|
|
284
|
+
try {
|
|
285
|
+
const backendUrl = requireBackendUrl();
|
|
286
|
+
const spec = await resolveFunction(state, backendUrl, name, "query");
|
|
287
|
+
const value = await executeFunction(backendUrl, "query", spec.callPath, args, componentPath ?? spec.componentPath);
|
|
288
|
+
return ok({
|
|
289
|
+
ok: true,
|
|
290
|
+
value: value === void 0 ? null : value
|
|
291
|
+
});
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return fail(error);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
if (options.writes) for (const [toolName, kind] of [["run_mutation", "mutation"], ["run_action", "action"]]) server.registerTool(toolName, {
|
|
297
|
+
description: `在 dev 部署上执行 Convex ${kind}(${kind === "action" ? "可能写数据或调用外部服务" : "写数据"})并返回结果。仅在开启写工具时可用(vultro mcp --writes)。`,
|
|
298
|
+
inputSchema: {
|
|
299
|
+
name: z.string().describe("函数路径,例如 messages:send"),
|
|
300
|
+
args: z.optional(z.record(z.string(), z.unknown())).describe("函数参数(JSON 对象,默认 {})"),
|
|
301
|
+
componentPath: z.optional(z.string()).describe("组件函数的组件路径(可选)")
|
|
302
|
+
}
|
|
303
|
+
}, async ({ name, args, componentPath }) => {
|
|
304
|
+
try {
|
|
305
|
+
const backendUrl = requireBackendUrl();
|
|
306
|
+
const spec = await resolveFunction(state, backendUrl, name, kind);
|
|
307
|
+
const value = await executeFunction(backendUrl, kind, spec.callPath, args, componentPath ?? spec.componentPath);
|
|
308
|
+
return ok({
|
|
309
|
+
ok: true,
|
|
310
|
+
value: value === void 0 ? null : value
|
|
311
|
+
});
|
|
312
|
+
} catch (error) {
|
|
313
|
+
return fail(error);
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
server.registerTool("list_tables", { description: "列出 dev 部署数据库中的所有表(schema 内的表名)。" }, async () => {
|
|
317
|
+
try {
|
|
318
|
+
const mapping = await postQuery(requireBackendUrl(), "_system/frontend/getTableMapping", {});
|
|
319
|
+
return ok({
|
|
320
|
+
ok: true,
|
|
321
|
+
tables: Object.values(mapping ?? {}).sort()
|
|
322
|
+
});
|
|
323
|
+
} catch (error) {
|
|
324
|
+
return fail(error);
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
server.registerTool("table_data", {
|
|
328
|
+
description: "分页读取一张表的文档。",
|
|
329
|
+
inputSchema: {
|
|
330
|
+
table: z.string().describe("表名"),
|
|
331
|
+
limit: z.optional(z.number().int().min(1).max(200)).describe("每页文档数(默认 10,最大 200)"),
|
|
332
|
+
cursor: z.optional(z.string()).describe("上一页响应里的 continueCursor;首页省略")
|
|
333
|
+
}
|
|
334
|
+
}, async ({ table, limit, cursor }) => {
|
|
335
|
+
try {
|
|
336
|
+
const data = await postQuery(requireBackendUrl(), "_system/frontend/paginatedTableDocuments", {
|
|
337
|
+
table,
|
|
338
|
+
paginationOpts: {
|
|
339
|
+
numItems: Math.max(1, Math.min(Number(limit ?? 10), 200)),
|
|
340
|
+
cursor: cursor ?? "0"
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
return ok({
|
|
344
|
+
ok: true,
|
|
345
|
+
table,
|
|
346
|
+
documents: data?.page ?? [],
|
|
347
|
+
isDone: data?.isDone ?? true,
|
|
348
|
+
continueCursor: data?.continueCursor ?? ""
|
|
349
|
+
});
|
|
350
|
+
} catch (error) {
|
|
351
|
+
return fail(error);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
server.registerTool("function_spec", { description: "列出部署的函数 API:每个 query/mutation/action 的路径与可见性。用于发现可调用函数。" }, async () => {
|
|
355
|
+
try {
|
|
356
|
+
return ok({
|
|
357
|
+
ok: true,
|
|
358
|
+
functions: (await loadFunctions(state, requireBackendUrl())).map((fn) => ({
|
|
359
|
+
path: fn.path,
|
|
360
|
+
type: fn.type,
|
|
361
|
+
visibility: fn.visibility,
|
|
362
|
+
callable: fn.visibility === "public" || options.allowInternal
|
|
363
|
+
}))
|
|
364
|
+
});
|
|
365
|
+
} catch (error) {
|
|
366
|
+
return fail(error);
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
server.registerTool("schema", { description: "返回 dev 部署声明的 schema:每张表的字段、索引、searchIndex 与 vectorIndex。" }, async () => {
|
|
370
|
+
try {
|
|
371
|
+
const schema = await postQuery(requireBackendUrl(), "_system/frontend/getSchemas", {});
|
|
372
|
+
let parsed = schema?.active;
|
|
373
|
+
try {
|
|
374
|
+
parsed = schema?.active ? JSON.parse(schema.active) : parsed;
|
|
375
|
+
} catch {}
|
|
376
|
+
return ok({
|
|
377
|
+
ok: true,
|
|
378
|
+
schema: parsed
|
|
379
|
+
});
|
|
380
|
+
} catch (error) {
|
|
381
|
+
return fail(error);
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
server.registerTool("logs", {
|
|
385
|
+
description: "拉取最近的函数执行日志(最新在前):函数名、类型、耗时、console 输出与错误。用于调试失败的函数。",
|
|
386
|
+
inputSchema: { limit: z.optional(z.number().int().min(1).max(500)).describe("最多返回条数(默认 50)") }
|
|
387
|
+
}, async ({ limit }) => {
|
|
388
|
+
try {
|
|
389
|
+
const backendUrl = requireBackendUrl();
|
|
390
|
+
const count = Math.max(1, Math.min(Number(limit ?? 50), 500));
|
|
391
|
+
const response = await fetch(`${backendUrl}/api/app_metrics/stream_function_logs?cursor=0`, { headers: authHeaders() });
|
|
392
|
+
if (!response.ok) throw new Error(`后端返回 ${response.status}(stream_function_logs)`);
|
|
393
|
+
return ok({
|
|
394
|
+
ok: true,
|
|
395
|
+
entries: ((await response.json()).entries ?? []).slice(-count).reverse()
|
|
396
|
+
});
|
|
397
|
+
} catch (error) {
|
|
398
|
+
return fail(error);
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
server.registerTool("scheduled_functions", { description: "列出定时任务(scheduled jobs)与 cron:状态、计划时间、最近一次运行结果。" }, async () => {
|
|
402
|
+
try {
|
|
403
|
+
const backendUrl = requireBackendUrl();
|
|
404
|
+
const [jobs, crons] = await Promise.all([postQuery(backendUrl, "_system/frontend/paginatedScheduledJobs", {}), postQuery(backendUrl, "_system/frontend/listCronJobs", {})]);
|
|
405
|
+
return ok({
|
|
406
|
+
ok: true,
|
|
407
|
+
scheduled: jobs ?? [],
|
|
408
|
+
crons: crons ?? []
|
|
409
|
+
});
|
|
410
|
+
} catch (error) {
|
|
411
|
+
return fail(error);
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
return server;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* `vultro mcp` 入口:把 MCP server 挂在 stdin/stdout 上常驻,直到对端关闭。
|
|
418
|
+
*
|
|
419
|
+
* 横幅信息走 **stderr**:stdio 是 MCP 协议通道,任何多余的 stdout 输出都会
|
|
420
|
+
* 破坏 agent harness 的 JSON 解析。
|
|
421
|
+
*/
|
|
422
|
+
async function runMcp(options, version) {
|
|
423
|
+
const server = createMcpServer(createMcpState(options), version);
|
|
424
|
+
const resolution = resolveBackendUrl(options);
|
|
425
|
+
const backend = resolution ? `${resolution.url}(来自 ${resolution.source})` : "未发现运行中的 dev server(启动 `vultro dev` 或传 --url / --port)";
|
|
426
|
+
process.stderr.write(`vultro mcp: 通过 stdio 提供 Vultro 后端工具(后端: ${backend},${options.writes ? "已开启写工具" : "只读(--writes 开启 mutation/action)"})\n`);
|
|
427
|
+
const transport = new StdioServerTransport();
|
|
428
|
+
await server.connect(transport);
|
|
429
|
+
await new Promise((resolveDone) => {
|
|
430
|
+
const check = setInterval(() => {
|
|
431
|
+
if (!server.isConnected()) {
|
|
432
|
+
clearInterval(check);
|
|
433
|
+
resolveDone();
|
|
434
|
+
}
|
|
435
|
+
}, 250);
|
|
436
|
+
check.unref?.();
|
|
437
|
+
});
|
|
438
|
+
return 0;
|
|
439
|
+
}
|
|
440
|
+
export { McpPolicyError, createMcpServer, createMcpState, executeFunction, findActiveAgentStatus, loadFunctions, matchesAllowlist, mcpOptionsFromCli, postQuery, resolveBackendUrl, resolveFunction, runMcp };
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { type AnyValidator, type SchemaInfo } from "@vultro/core";
|
|
2
|
+
/** 用户函数元数据。 */
|
|
3
|
+
export interface FunctionExport {
|
|
4
|
+
/** 导出名,例如 `send`。 */
|
|
5
|
+
name: string;
|
|
6
|
+
kind: "query" | "mutation" | "action" | "httpAction";
|
|
7
|
+
visibility: "public" | "internal";
|
|
8
|
+
argsValidator?: AnyValidator;
|
|
9
|
+
returnsValidator?: AnyValidator;
|
|
10
|
+
}
|
|
11
|
+
/** 一个 `convex/` 模块。 */
|
|
12
|
+
export interface ConvexModule {
|
|
13
|
+
/** 相对 `convex/` 的路径(无扩展名,使用 `/`),例如 `admin/users`。 */
|
|
14
|
+
name: string;
|
|
15
|
+
/** 相对项目根目录的路径,用于错误提示。 */
|
|
16
|
+
relativePath: string;
|
|
17
|
+
/** 绝对路径。 */
|
|
18
|
+
filePath: string;
|
|
19
|
+
functions: FunctionExport[];
|
|
20
|
+
}
|
|
21
|
+
/** 原始 schema 的宽松形状;只用来读取 check 需要的元数据。 */
|
|
22
|
+
export interface RawSchemaLike {
|
|
23
|
+
tables?: Record<string, RawTableLike>;
|
|
24
|
+
}
|
|
25
|
+
interface RawTableLike {
|
|
26
|
+
validator?: AnyValidator;
|
|
27
|
+
export?: () => {
|
|
28
|
+
indexes?: Array<{
|
|
29
|
+
indexDescriptor: string;
|
|
30
|
+
fields: string[];
|
|
31
|
+
}>;
|
|
32
|
+
stagedDbIndexes?: Array<{
|
|
33
|
+
indexDescriptor: string;
|
|
34
|
+
fields: string[];
|
|
35
|
+
}>;
|
|
36
|
+
searchIndexes?: unknown[];
|
|
37
|
+
stagedSearchIndexes?: unknown[];
|
|
38
|
+
vectorIndexes?: unknown[];
|
|
39
|
+
stagedVectorIndexes?: unknown[];
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** 加载后的项目。 */
|
|
43
|
+
/** 通过 `convex/convex.config.ts` 发现的一个组件。 */
|
|
44
|
+
export interface ProjectComponent {
|
|
45
|
+
/** 当前层级内的挂载名(`app.use(component, { name })` 或默认名)。 */
|
|
46
|
+
name: string;
|
|
47
|
+
/** 完整组件路径,例如 `counter` 或 `counter.notes`。 */
|
|
48
|
+
path: string;
|
|
49
|
+
/** defineComponent("...") 中的默认名称。 */
|
|
50
|
+
defaultName: string;
|
|
51
|
+
/** 组件自身的 `convex.config.ts`。 */
|
|
52
|
+
configPath: string;
|
|
53
|
+
/** 组件包根目录(包含 convex/ 的目录)。 */
|
|
54
|
+
rootDir: string;
|
|
55
|
+
/** 组件的 convex/ 目录。 */
|
|
56
|
+
convexDir: string;
|
|
57
|
+
schemaPath?: string;
|
|
58
|
+
schemaExportName?: "default" | "schema";
|
|
59
|
+
/** 组件的函数模块(不含 schema / _generated)。 */
|
|
60
|
+
modules: Array<{
|
|
61
|
+
name: string;
|
|
62
|
+
filePath: string;
|
|
63
|
+
/** 函数导出元数据,用于生成带类型的组件引用树。 */
|
|
64
|
+
functions: FunctionExport[];
|
|
65
|
+
}>;
|
|
66
|
+
/** 组件继续 mount 的子组件。 */
|
|
67
|
+
children: ProjectComponent[];
|
|
68
|
+
}
|
|
69
|
+
export interface ConvexProject {
|
|
70
|
+
/** 包含 `convex/` 的项目根目录(绝对路径)。 */
|
|
71
|
+
rootDir: string;
|
|
72
|
+
/** `convex/` 目录(绝对路径)。 */
|
|
73
|
+
convexDir: string;
|
|
74
|
+
/** `convex/schema.ts`(如果存在)。 */
|
|
75
|
+
schemaPath?: string;
|
|
76
|
+
/** schema 模块使用 default 导出还是具名 `schema` 导出。 */
|
|
77
|
+
schemaExportName?: "default" | "schema";
|
|
78
|
+
/** 原始 schema 定义。 */
|
|
79
|
+
rawSchema?: RawSchemaLike;
|
|
80
|
+
/** 归一化后的 schema。 */
|
|
81
|
+
schema: SchemaInfo;
|
|
82
|
+
/** 所有包含函数的模块,按路径排序。 */
|
|
83
|
+
modules: ConvexModule[];
|
|
84
|
+
/** 所有源码文件(包含没有函数的 helper / schema),用于静态扫描。 */
|
|
85
|
+
sourceFiles: string[];
|
|
86
|
+
/** 加载失败的模块;check 会逐条报告,codegen 则直接拒绝生成。 */
|
|
87
|
+
moduleErrors: ModuleLoadError[];
|
|
88
|
+
/** `convex/convex.config.ts` 中 mount 的组件。 */
|
|
89
|
+
components: ProjectComponent[];
|
|
90
|
+
}
|
|
91
|
+
/** 单个模块的加载错误。 */
|
|
92
|
+
export interface ModuleLoadError {
|
|
93
|
+
/** 相对项目根目录的路径。 */
|
|
94
|
+
relativePath: string;
|
|
95
|
+
message: string;
|
|
96
|
+
}
|
|
97
|
+
export declare class ProjectError extends Error {
|
|
98
|
+
}
|
|
99
|
+
export interface LoadProjectOptions {
|
|
100
|
+
/** 起始目录;默认当前工作目录。 */
|
|
101
|
+
dir?: string;
|
|
102
|
+
/**
|
|
103
|
+
* codegen 在首次运行时需要先生成 `_generated/server.js`,否则用户模块
|
|
104
|
+
* 顶部的 `import { query } from "./_generated/server"` 会加载失败。
|
|
105
|
+
* check 不会自动写文件,因此传 false。
|
|
106
|
+
*/
|
|
107
|
+
bootstrapGeneratedServer?: boolean;
|
|
108
|
+
/**
|
|
109
|
+
* 导入模块前清空项目源码的模块缓存。
|
|
110
|
+
*
|
|
111
|
+
* 常驻进程(Vite dev server / 测试)会反复调用 codegen;运行时的 `import()`
|
|
112
|
+
* 缓存不会因为文件改动自动失效,不清缓存就会一直读到旧模块。CLI 单次
|
|
113
|
+
* 执行时清缓存几乎没有成本,因此默认开启。
|
|
114
|
+
*/
|
|
115
|
+
refreshModules?: boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* 清空 `roots` 目录下(不含 `node_modules`)已加载模块的缓存。
|
|
119
|
+
*
|
|
120
|
+
* Bun 会把 ESM `import()` 的结果同样登记在 `require.cache` 里,删除条目后
|
|
121
|
+
* 下一次 `import()` 会重新读取磁盘;Node 的 ESM 缓存不暴露且无法失效,
|
|
122
|
+
* 因此这个函数只对 Bun 生效(其它运行时返回 0,由调用方回退到子进程)。
|
|
123
|
+
*
|
|
124
|
+
* 只清理项目自己的源码,避免把 `@vultro/core`、`convex` 等依赖也重新求值,
|
|
125
|
+
* 那会破坏模块单例(例如 `instanceof` 判断、运行时全局状态)。
|
|
126
|
+
*/
|
|
127
|
+
export declare function clearModuleCache(roots: string[]): number;
|
|
128
|
+
/**
|
|
129
|
+
* 从任意目录向上寻找包含 `convex/` 的项目根目录。
|
|
130
|
+
*
|
|
131
|
+
* 允许在项目子目录里执行 `vultro codegen`,行为与 `convex`
|
|
132
|
+
* 的“从当前目录开始向上找”一致。
|
|
133
|
+
*/
|
|
134
|
+
export declare function findProjectDir(start?: string): string;
|
|
135
|
+
/** 递归列出 `convex/` 下的源码文件。 */
|
|
136
|
+
export declare function discoverSourceFiles(convexDir: string): string[];
|
|
137
|
+
/**
|
|
138
|
+
* 加载项目 schema 与函数模块。
|
|
139
|
+
*
|
|
140
|
+
* 任一模块加载失败都会抛出 `ProjectError`,并在消息中带上相对路径,
|
|
141
|
+
* 避免用户只看到一个裸的 `Cannot find module`。
|
|
142
|
+
*/
|
|
143
|
+
export declare function loadProject(options?: LoadProjectOptions): Promise<ConvexProject>;
|
|
144
|
+
/**
|
|
145
|
+
* 把 Bun 安装器返回的真实路径还原成包管理器提供的稳定符号链接路径。
|
|
146
|
+
*
|
|
147
|
+
* Bun 把依赖放在 `node_modules/.bun/<包名>@<版本>+<内容哈希>/node_modules/`
|
|
148
|
+
* 下,`require.resolve` 默认返回这个真实路径。codegen 会把组件的
|
|
149
|
+
* schema / 函数模块路径写进已提交的 `_generated/components.ts`,一旦
|
|
150
|
+
* 路径里带上版本或内容哈希,重新安装依赖(例如 CI 上)就会让同样的源码
|
|
151
|
+
* 生成出不同的 import 路径,`git diff --exit-code` 随之失败。
|
|
152
|
+
*
|
|
153
|
+
* 因此这里按「包内相对路径」反查项目里的符号链接目录
|
|
154
|
+
* (`node_modules/<包名>/...`),输出只和包名、文件位置有关。
|
|
155
|
+
* 找不到对应符号链接时退回真实路径,保证 codegen 仍然可用。
|
|
156
|
+
*
|
|
157
|
+
* @param resolvedPath `require.resolve` 得到的绝对路径
|
|
158
|
+
* @param searchDirs 依次尝试的起始目录(项目根目录优先,其次组件所在目录)
|
|
159
|
+
*/
|
|
160
|
+
export declare function stabilizePackagePath(resolvedPath: string, searchDirs: string[]): string;
|
|
161
|
+
/**
|
|
162
|
+
* 检查 `foo.ts` 与 `foo/bar.ts` 这种文件 / 目录同名冲突。
|
|
163
|
+
*
|
|
164
|
+
* Convex 的 API 树用模块路径作为命名空间;一个路径不能同时是函数模块
|
|
165
|
+
* 和目录。提前报告比让 codegen 生成出错误类型更友好。
|
|
166
|
+
*/
|
|
167
|
+
export declare function findModulePathConflicts(modules: ConvexModule[]): string[];
|
|
168
|
+
/** 收集模块中所有 Vultro 函数导出。 */
|
|
169
|
+
export declare function collectFunctions(loaded: Record<string, unknown>): FunctionExport[];
|
|
170
|
+
/** 读取文本文件;check 的静态扫描使用。 */
|
|
171
|
+
export declare function readSource(filePath: string): string;
|
|
172
|
+
export {};
|