@codetelemetry/mcp 0.3.14 → 0.4.1
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 +97 -1
- package/dist/src/client/bin.js +8 -1
- package/dist/src/client/bootstrap.d.ts +28 -0
- package/dist/src/client/bootstrap.js +590 -0
- package/dist/src/client/bootstrapGitHub.d.ts +21 -0
- package/dist/src/client/bootstrapGitHub.js +157 -0
- package/dist/src/client/cli.js +64 -0
- package/dist/src/client/graderArtifact.js +2 -2
- package/dist/src/client/index.d.ts +2 -0
- package/dist/src/client/index.js +2 -0
- package/dist/src/client/repositoryHook.d.ts +1 -0
- package/dist/src/client/repositoryHook.js +31 -0
- package/dist/src/client/workspaces.d.ts +45 -0
- package/dist/src/client/workspaces.js +384 -0
- package/dist/src/mcpServer.js +1 -1
- package/dist/src/session.d.ts +1 -1
- package/dist/src/tools.d.ts +4 -0
- package/dist/src/tools.js +24 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/workspaceRuntime.d.ts +5 -0
- package/dist/src/workspaceRuntime.js +187 -0
- package/package.json +1 -1
- package/tool-manifest.json +128 -3
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { buildOtelSection } from "./codexConfig.js";
|
|
6
|
+
import { repositoryHookSource, quotedCommand, REPOSITORY_HOOK_FILE } from "./repositoryHook.js";
|
|
7
|
+
import { looksLikeKey } from "./keys.js";
|
|
8
|
+
export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.4.1";
|
|
9
|
+
export const MAX_WORKSPACE_BYTES = 64 * 1024;
|
|
10
|
+
export const MAX_WORKSPACES = 64;
|
|
11
|
+
export function workspaceName(value) {
|
|
12
|
+
if (typeof value !== "string" ||
|
|
13
|
+
looksLikeKey(value) ||
|
|
14
|
+
!/^[a-z][a-z0-9_-]{0,63}$/.test(value))
|
|
15
|
+
throw new Error("Workspace name must be 1–64 lowercase letters, digits, underscores or hyphens, starting with a letter.");
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
export function workspaceOrigin(value) {
|
|
19
|
+
if (typeof value !== "string" || value.length > 2048)
|
|
20
|
+
throw new Error("Invalid workspace service origin.");
|
|
21
|
+
const url = new URL(value);
|
|
22
|
+
if (url.username ||
|
|
23
|
+
url.password ||
|
|
24
|
+
url.search ||
|
|
25
|
+
url.hash ||
|
|
26
|
+
url.pathname !== "/" ||
|
|
27
|
+
(url.protocol !== "https:" &&
|
|
28
|
+
!(url.protocol === "http:" &&
|
|
29
|
+
["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))))
|
|
30
|
+
throw new Error("Workspace endpoints require an HTTPS origin (HTTP is allowed on loopback).");
|
|
31
|
+
return url.origin;
|
|
32
|
+
}
|
|
33
|
+
export function workspaceScope(value) {
|
|
34
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
35
|
+
throw new Error("Invalid workspace scope.");
|
|
36
|
+
const s = value;
|
|
37
|
+
if ([s.tenantId, s.billingAccountId].some((v) => typeof v !== "string" || !v || v.length > 256) ||
|
|
38
|
+
(s.teamId !== null &&
|
|
39
|
+
(typeof s.teamId !== "string" ||
|
|
40
|
+
!/^tm_[a-zA-Z0-9_-]{1,128}$/.test(s.teamId))))
|
|
41
|
+
throw new Error("Invalid workspace scope.");
|
|
42
|
+
return {
|
|
43
|
+
tenantId: s.tenantId,
|
|
44
|
+
teamId: s.teamId,
|
|
45
|
+
billingAccountId: s.billingAccountId,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function bindingOf(value) {
|
|
49
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
50
|
+
throw new Error("Invalid workspace context.");
|
|
51
|
+
const v = value;
|
|
52
|
+
if (v.version !== 1)
|
|
53
|
+
throw new Error("Unsupported workspace context version; upgrade CodeTelemetry.");
|
|
54
|
+
return {
|
|
55
|
+
version: 1,
|
|
56
|
+
name: workspaceName(v.name),
|
|
57
|
+
apiBase: workspaceOrigin(v.apiBase),
|
|
58
|
+
scope: workspaceScope(v.scope),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export function sameWorkspace(a, b) {
|
|
62
|
+
return (a.name === b.name &&
|
|
63
|
+
a.apiBase === b.apiBase &&
|
|
64
|
+
a.scope.tenantId === b.scope.tenantId &&
|
|
65
|
+
a.scope.teamId === b.scope.teamId &&
|
|
66
|
+
a.scope.billingAccountId === b.scope.billingAccountId);
|
|
67
|
+
}
|
|
68
|
+
export function workspaceHome() {
|
|
69
|
+
const dir = process.env.CODETELEMETRY_CONTEXT_HOME ||
|
|
70
|
+
path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "codetelemetry", "workspaces");
|
|
71
|
+
if (!path.isAbsolute(dir))
|
|
72
|
+
throw new Error("CODETELEMETRY_CONTEXT_HOME must be absolute.");
|
|
73
|
+
return path.resolve(dir);
|
|
74
|
+
}
|
|
75
|
+
function noLinks(file) {
|
|
76
|
+
let current = path.parse(file).root;
|
|
77
|
+
for (const segment of path
|
|
78
|
+
.resolve(file)
|
|
79
|
+
.slice(current.length)
|
|
80
|
+
.split(path.sep)) {
|
|
81
|
+
current = path.join(current, segment);
|
|
82
|
+
try {
|
|
83
|
+
if (fs.lstatSync(current).isSymbolicLink())
|
|
84
|
+
throw new Error("Workspace paths cannot contain symbolic links.");
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error.code !== "ENOENT")
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function readWorkspaceFile(file, privateFile = true) {
|
|
93
|
+
noLinks(file);
|
|
94
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
95
|
+
try {
|
|
96
|
+
const st = fs.fstatSync(fd);
|
|
97
|
+
if (!st.isFile() ||
|
|
98
|
+
st.size > MAX_WORKSPACE_BYTES ||
|
|
99
|
+
(privateFile &&
|
|
100
|
+
process.platform !== "win32" &&
|
|
101
|
+
((st.mode & 0o077) !== 0 || st.uid !== process.getuid?.())))
|
|
102
|
+
throw new Error("Workspace state must be an owned private regular file of at most 64 KiB.");
|
|
103
|
+
const bytes = Buffer.alloc(MAX_WORKSPACE_BYTES + 1);
|
|
104
|
+
const count = fs.readSync(fd, bytes, 0, bytes.length, 0);
|
|
105
|
+
if (count > MAX_WORKSPACE_BYTES)
|
|
106
|
+
throw new Error("Workspace state exceeds 64 KiB.");
|
|
107
|
+
try {
|
|
108
|
+
return JSON.parse(bytes.subarray(0, count).toString("utf8"));
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
throw new Error("Invalid workspace JSON; inspect the private state file.");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
fs.closeSync(fd);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
export function writeWorkspaceText(file, data) {
|
|
119
|
+
if (Buffer.byteLength(data) > MAX_WORKSPACE_BYTES)
|
|
120
|
+
throw new Error("Workspace state exceeds 64 KiB.");
|
|
121
|
+
noLinks(file);
|
|
122
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
123
|
+
noLinks(file);
|
|
124
|
+
if (fs.existsSync(file) && !fs.lstatSync(file).isFile())
|
|
125
|
+
throw new Error("Workspace state must be a regular file.");
|
|
126
|
+
const tmp = `${file}.${randomBytes(12).toString("hex")}.tmp`;
|
|
127
|
+
const fd = fs.openSync(tmp, "wx", 0o600);
|
|
128
|
+
try {
|
|
129
|
+
fs.writeFileSync(fd, data);
|
|
130
|
+
fs.fsyncSync(fd);
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
fs.closeSync(fd);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
fs.renameSync(tmp, file);
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
fs.rmSync(tmp, { force: true });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export function writeWorkspaceFile(file, value) {
|
|
143
|
+
writeWorkspaceText(file, JSON.stringify(value, null, 2) + "\n");
|
|
144
|
+
}
|
|
145
|
+
export function codexWorkspaceProfilePath(name) {
|
|
146
|
+
return path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), `codetelemetry-${workspaceName(name)}.config.toml`);
|
|
147
|
+
}
|
|
148
|
+
export function workspaceCaptureDefault(context) {
|
|
149
|
+
if (context.clientConfig)
|
|
150
|
+
return context.clientConfig.enrich;
|
|
151
|
+
const file = codexWorkspaceProfilePath(context.name);
|
|
152
|
+
if (!fs.existsSync(file))
|
|
153
|
+
return true;
|
|
154
|
+
noLinks(file);
|
|
155
|
+
const stat = fs.lstatSync(file);
|
|
156
|
+
if (!stat.isFile() || stat.size > MAX_WORKSPACE_BYTES)
|
|
157
|
+
throw new Error("Invalid workspace profile.");
|
|
158
|
+
const text = fs.readFileSync(file, "utf8");
|
|
159
|
+
if (!text.startsWith(`# CodeTelemetry workspace ${context.name}\n`)) {
|
|
160
|
+
throw new Error("The Codex workspace profile is not managed by CodeTelemetry; choose a different context name.");
|
|
161
|
+
}
|
|
162
|
+
const section = text.match(/^\[otel\]\r?\n([\s\S]*?)(?=^\[|(?![\s\S]))/m)?.[1] ?? "";
|
|
163
|
+
return /^\s*log_user_prompt\s*=\s*true\s*(?:#.*)?$/m.test(section);
|
|
164
|
+
}
|
|
165
|
+
export function writeCodexWorkspaceProfile(context, options = {}) {
|
|
166
|
+
const enrich = options.enrich ?? workspaceCaptureDefault(context);
|
|
167
|
+
const profilePath = codexWorkspaceProfilePath(context.name), marker = `# CodeTelemetry workspace ${context.name}\n`;
|
|
168
|
+
upgradeLegacyCodexObserver(path.dirname(profilePath));
|
|
169
|
+
if (fs.existsSync(profilePath)) {
|
|
170
|
+
noLinks(profilePath);
|
|
171
|
+
const st = fs.lstatSync(profilePath);
|
|
172
|
+
if (!st.isFile() ||
|
|
173
|
+
st.size > MAX_WORKSPACE_BYTES ||
|
|
174
|
+
!fs.readFileSync(profilePath, "utf8").startsWith(marker))
|
|
175
|
+
throw new Error("The Codex workspace profile is not managed by CodeTelemetry; choose a different context name.");
|
|
176
|
+
}
|
|
177
|
+
let text = marker +
|
|
178
|
+
buildOtelSection(context.ingestKey, context.ingestEndpoint, enrich) +
|
|
179
|
+
"\n";
|
|
180
|
+
if (!enrich)
|
|
181
|
+
text = text.replace("[otel]\n", "[otel]\nlog_user_prompt = false\n");
|
|
182
|
+
if (options.repositoryObservation) {
|
|
183
|
+
const hookPath = path.join(workspaceHome(), `${context.name}.hook.cjs`);
|
|
184
|
+
writeWorkspaceText(hookPath, repositoryHookSource({ codexConfigPath: profilePath, workspaceName: context.name }));
|
|
185
|
+
for (const event of ["SessionStart", "UserPromptSubmit", "PostToolUse"])
|
|
186
|
+
text += `\n[[hooks.${event}]]\n[[hooks.${event}.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(quotedCommand(hookPath))}\ntimeout = 3\n`;
|
|
187
|
+
}
|
|
188
|
+
const basePath = path.join(path.dirname(profilePath), "config.toml");
|
|
189
|
+
let base = "";
|
|
190
|
+
if (fs.existsSync(basePath)) {
|
|
191
|
+
if (fs.statSync(basePath).size > 1024 * 1024)
|
|
192
|
+
throw new Error("Base Codex configuration exceeds 1 MiB.");
|
|
193
|
+
base = fs.readFileSync(basePath, "utf8");
|
|
194
|
+
}
|
|
195
|
+
if (/^\s*\[\s*["']?mcp_servers["']?\s*\.\s*["']?codetelemetry["']?\s*\]\s*(?:#.*)?$/m.test(base) ||
|
|
196
|
+
/^\s*mcp_servers\s*\.\s*codetelemetry\s*\.\s*(?:command|url)\s*=/m.test(base))
|
|
197
|
+
text += "\n[mcp_servers.codetelemetry]\nenabled = false\n";
|
|
198
|
+
text += `\n[mcp_servers.codetelemetry_workspace]\ncommand = "npx"\nargs = ["-y", "--package=${WORKSPACE_MCP_PACKAGE}", "codetelemetry-mcp"]\n\n[mcp_servers.codetelemetry_workspace.env]\nCODETELEMETRY_WORKSPACE = ${JSON.stringify(context.name)}\nCODETELEMETRY_CONTEXT_HOME = ${JSON.stringify(workspaceHome())}\n`;
|
|
199
|
+
writeWorkspaceText(profilePath, text);
|
|
200
|
+
return { path: profilePath };
|
|
201
|
+
}
|
|
202
|
+
function upgradeLegacyCodexObserver(codexHome) {
|
|
203
|
+
const file = path.join(codexHome, REPOSITORY_HOOK_FILE);
|
|
204
|
+
if (!fs.existsSync(file))
|
|
205
|
+
return;
|
|
206
|
+
noLinks(file);
|
|
207
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
208
|
+
let source;
|
|
209
|
+
try {
|
|
210
|
+
const st = fs.fstatSync(fd);
|
|
211
|
+
if (!st.isFile() || st.size > MAX_WORKSPACE_BYTES ||
|
|
212
|
+
(process.platform !== "win32" && (st.uid !== process.getuid?.() || (st.mode & 0o077) !== 0)))
|
|
213
|
+
throw new Error("Existing CodeTelemetry observer must be an owned private regular file.");
|
|
214
|
+
const bytes = Buffer.alloc(MAX_WORKSPACE_BYTES + 1);
|
|
215
|
+
const count = fs.readSync(fd, bytes, 0, bytes.length, 0);
|
|
216
|
+
if (count > MAX_WORKSPACE_BYTES)
|
|
217
|
+
throw new Error("Existing CodeTelemetry observer exceeds 64 KiB.");
|
|
218
|
+
source = bytes.subarray(0, count).toString("utf8");
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
fs.closeSync(fd);
|
|
222
|
+
}
|
|
223
|
+
const configPath = path.join(codexHome, "config.toml");
|
|
224
|
+
const updated = repositoryHookSource({ codexConfigPath: configPath });
|
|
225
|
+
if (source === updated)
|
|
226
|
+
return;
|
|
227
|
+
const declaration = `const codexConfigPath = ${JSON.stringify(configPath)};`;
|
|
228
|
+
const fingerprint = createHash("sha256").update(source.replace(declaration, 'const codexConfigPath = "";')).digest("hex");
|
|
229
|
+
const recognized = new Set([
|
|
230
|
+
"69dd5ad120636379875fc411bcaaa096defe475944d24a6e899dc9796472ab2d",
|
|
231
|
+
"65eaa30f6c565b0298137986bbe4e94d0435f8fedc2574fa284e7979a5fa9ef4",
|
|
232
|
+
]);
|
|
233
|
+
if (!source.includes(declaration) || !recognized.has(fingerprint))
|
|
234
|
+
throw new Error("Existing CodeTelemetry observer differs from a recognized client release. Review or update that helper before configuring a workspace; its global hook definitions were preserved.");
|
|
235
|
+
writeWorkspaceText(file, updated);
|
|
236
|
+
}
|
|
237
|
+
export function workspaceEntries() {
|
|
238
|
+
noLinks(workspaceHome());
|
|
239
|
+
if (!fs.existsSync(workspaceHome()))
|
|
240
|
+
return [];
|
|
241
|
+
const dir = fs.opendirSync(workspaceHome()), names = [];
|
|
242
|
+
try {
|
|
243
|
+
let entry;
|
|
244
|
+
while ((entry = dir.readSync()) !== null) {
|
|
245
|
+
names.push(entry.name);
|
|
246
|
+
if (names.length > MAX_WORKSPACES * 3)
|
|
247
|
+
throw new Error("Workspace store exceeds its entry bound.");
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
dir.closeSync();
|
|
252
|
+
}
|
|
253
|
+
return names;
|
|
254
|
+
}
|
|
255
|
+
export function workspaceLock(name) {
|
|
256
|
+
if (name !== ".store")
|
|
257
|
+
workspaceName(name);
|
|
258
|
+
noLinks(workspaceHome());
|
|
259
|
+
fs.mkdirSync(workspaceHome(), { recursive: true, mode: 0o700 });
|
|
260
|
+
workspaceEntries();
|
|
261
|
+
const file = path.join(workspaceHome(), `${name}.lock`);
|
|
262
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
263
|
+
try {
|
|
264
|
+
const fd = fs.openSync(file, "wx", 0o600);
|
|
265
|
+
try {
|
|
266
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid }));
|
|
267
|
+
}
|
|
268
|
+
finally {
|
|
269
|
+
fs.closeSync(fd);
|
|
270
|
+
}
|
|
271
|
+
return () => fs.unlinkSync(file);
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
if (error.code !== "EEXIST")
|
|
275
|
+
throw error;
|
|
276
|
+
const owner = readWorkspaceFile(file);
|
|
277
|
+
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0)
|
|
278
|
+
throw new Error("Workspace lock needs inspection.");
|
|
279
|
+
try {
|
|
280
|
+
process.kill(owner.pid, 0);
|
|
281
|
+
}
|
|
282
|
+
catch (e) {
|
|
283
|
+
if (e.code === "ESRCH") {
|
|
284
|
+
fs.unlinkSync(file);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
throw new Error("Another process is using this workspace; resume when it finishes.");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
throw new Error("Workspace lock changed; retry.");
|
|
292
|
+
}
|
|
293
|
+
export function contextPath(name) {
|
|
294
|
+
return path.join(workspaceHome(), `${workspaceName(name)}.json`);
|
|
295
|
+
}
|
|
296
|
+
export function loadWorkspace(name) {
|
|
297
|
+
const raw = readWorkspaceFile(contextPath(name));
|
|
298
|
+
const binding = bindingOf(raw);
|
|
299
|
+
if (binding.name !== name || !looksLikeKey(raw.ingestKey))
|
|
300
|
+
throw new Error("Workspace context has invalid identity or credentials.");
|
|
301
|
+
if (raw.clientConfig &&
|
|
302
|
+
(!["claude", "codex"].includes(raw.clientConfig.client) ||
|
|
303
|
+
typeof raw.clientConfig.path !== "string" ||
|
|
304
|
+
!path.isAbsolute(raw.clientConfig.path) ||
|
|
305
|
+
typeof raw.clientConfig.enrich !== "boolean" ||
|
|
306
|
+
typeof raw.clientConfig.repositoryObservation !== "boolean"))
|
|
307
|
+
throw new Error("Invalid workspace client configuration.");
|
|
308
|
+
return {
|
|
309
|
+
...binding,
|
|
310
|
+
ingestEndpoint: workspaceOrigin(raw.ingestEndpoint),
|
|
311
|
+
ingestKey: raw.ingestKey,
|
|
312
|
+
...(raw.clientConfig ? { clientConfig: raw.clientConfig } : {}),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
export function saveWorkspace(context) {
|
|
316
|
+
const release = workspaceLock(".store");
|
|
317
|
+
try {
|
|
318
|
+
let checked = {
|
|
319
|
+
...bindingOf(context),
|
|
320
|
+
ingestEndpoint: workspaceOrigin(context.ingestEndpoint),
|
|
321
|
+
ingestKey: context.ingestKey,
|
|
322
|
+
...(context.clientConfig ? { clientConfig: context.clientConfig } : {}),
|
|
323
|
+
};
|
|
324
|
+
if (!looksLikeKey(checked.ingestKey))
|
|
325
|
+
throw new Error("Invalid workspace credential.");
|
|
326
|
+
const file = contextPath(checked.name);
|
|
327
|
+
if (fs.existsSync(file)) {
|
|
328
|
+
const existing = loadWorkspace(checked.name);
|
|
329
|
+
if (!sameWorkspace(existing, checked))
|
|
330
|
+
throw new Error("Workspace identity changed; use a new context name.");
|
|
331
|
+
if (!checked.clientConfig && existing.clientConfig)
|
|
332
|
+
checked = { ...checked, clientConfig: existing.clientConfig };
|
|
333
|
+
}
|
|
334
|
+
fs.mkdirSync(workspaceHome(), { recursive: true, mode: 0o700 });
|
|
335
|
+
noLinks(workspaceHome());
|
|
336
|
+
if (!fs.existsSync(file) &&
|
|
337
|
+
workspaceEntries().filter((n) => /^[a-z][a-z0-9_-]{0,63}\.json$/.test(n))
|
|
338
|
+
.length >= MAX_WORKSPACES)
|
|
339
|
+
throw new Error("Workspace store is full; remove unused contexts before continuing.");
|
|
340
|
+
writeWorkspaceFile(file, checked);
|
|
341
|
+
}
|
|
342
|
+
finally {
|
|
343
|
+
release();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
export function listWorkspaces() {
|
|
347
|
+
if (!fs.existsSync(workspaceHome()))
|
|
348
|
+
return [];
|
|
349
|
+
noLinks(workspaceHome());
|
|
350
|
+
const names = workspaceEntries();
|
|
351
|
+
if (names.length > MAX_WORKSPACES * 3)
|
|
352
|
+
throw new Error("Workspace store exceeds its entry bound.");
|
|
353
|
+
const files = names.filter((n) => /^[a-z][a-z0-9_-]{0,63}\.json$/.test(n));
|
|
354
|
+
if (files.length > MAX_WORKSPACES)
|
|
355
|
+
throw new Error("Workspace store exceeds 64 contexts.");
|
|
356
|
+
return files
|
|
357
|
+
.sort()
|
|
358
|
+
.map((file) => bindingOf(loadWorkspace(file.slice(0, -5))));
|
|
359
|
+
}
|
|
360
|
+
export function findWorkspaceBinding(start = process.cwd()) {
|
|
361
|
+
let dir = path.resolve(start);
|
|
362
|
+
for (let depth = 0; depth < 64; depth++) {
|
|
363
|
+
const file = path.join(dir, ".codetelemetry", "workspace.json");
|
|
364
|
+
if (fs.existsSync(file))
|
|
365
|
+
return bindingOf(readWorkspaceFile(file, false));
|
|
366
|
+
if (fs.existsSync(path.join(dir, ".git")) || path.dirname(dir) === dir)
|
|
367
|
+
return null;
|
|
368
|
+
dir = path.dirname(dir);
|
|
369
|
+
}
|
|
370
|
+
throw new Error("Workspace binding search exceeded 64 parents.");
|
|
371
|
+
}
|
|
372
|
+
export function bindWorkspace(repositoryPath, context) {
|
|
373
|
+
const root = fs.realpathSync(repositoryPath);
|
|
374
|
+
if (!fs.statSync(root).isDirectory() ||
|
|
375
|
+
root === os.homedir() ||
|
|
376
|
+
root === path.parse(root).root)
|
|
377
|
+
throw new Error("Choose a repository directory.");
|
|
378
|
+
const file = path.join(root, ".codetelemetry", "workspace.json");
|
|
379
|
+
if (fs.existsSync(file) &&
|
|
380
|
+
!sameWorkspace(bindingOf(readWorkspaceFile(file, false)), context))
|
|
381
|
+
throw new Error("Repository is bound to another workspace; remove its binding explicitly before switching.");
|
|
382
|
+
writeWorkspaceFile(file, bindingOf(context));
|
|
383
|
+
return file;
|
|
384
|
+
}
|
package/dist/src/mcpServer.js
CHANGED
|
@@ -30,7 +30,7 @@ export function buildServer(ctx) {
|
|
|
30
30
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: manifestEntries(TOOLS) }));
|
|
31
31
|
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
32
32
|
const result = await callTool(req.params.name, (req.params.arguments ?? {}), ctx);
|
|
33
|
-
if (["interpret_session", "read_session_events", "compare_sessions", "plan_next_session", "seed_grader_config", "get_grader_config", "update_grader_config", "publish_grader_config", "write_grader_config_artifact"].includes(req.params.name))
|
|
33
|
+
if (["workspace_context", "bootstrap_workspace", "interpret_session", "read_session_events", "compare_sessions", "plan_next_session", "seed_grader_config", "get_grader_config", "update_grader_config", "publish_grader_config", "write_grader_config_artifact"].includes(req.params.name))
|
|
34
34
|
return boundedToolResponse(result);
|
|
35
35
|
return {
|
|
36
36
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
package/dist/src/session.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExpectedKeyScope, KeyScope } from "./client/connectivity.ts";
|
|
2
|
-
export type KeySource = "device-flow" | "pasted";
|
|
2
|
+
export type KeySource = "device-flow" | "pasted" | "workspace";
|
|
3
3
|
export declare class OnboardingSession {
|
|
4
4
|
#private;
|
|
5
5
|
keyHash: string | null;
|
package/dist/src/tools.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import type { WorkspaceBinding } from "./client/workspaces.ts";
|
|
1
2
|
import path from "node:path";
|
|
2
3
|
import { type FetchLike, type OnboardClient } from "./client/index.ts";
|
|
3
4
|
import { OnboardingSession } from "./session.ts";
|
|
4
5
|
export type ToolContext = {
|
|
5
6
|
session: OnboardingSession;
|
|
7
|
+
workspace?: WorkspaceBinding;
|
|
8
|
+
workspaceInitialized?: boolean;
|
|
9
|
+
workspaceClient?: "claude" | "codex";
|
|
6
10
|
endpointsOverride?: {
|
|
7
11
|
apiBase?: string;
|
|
8
12
|
ingestEndpoint?: string;
|
package/dist/src/tools.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { workspaceTools, restoreWorkspace } from "./workspaceRuntime.js";
|
|
1
2
|
import fs from "node:fs";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
@@ -515,6 +516,7 @@ async function requestGrader(ctx, operation, body) {
|
|
|
515
516
|
: "Read every page needed before changing or publishing existing checks. Use revision as expectedRevision when saving or publishing. Draft checks affect scoring after publish_grader_config." };
|
|
516
517
|
}
|
|
517
518
|
export const TOOLS = [
|
|
519
|
+
...workspaceTools,
|
|
518
520
|
{
|
|
519
521
|
name: "authenticate",
|
|
520
522
|
title: "Authenticate (device code)",
|
|
@@ -1788,7 +1790,28 @@ export async function callTool(name, args, ctx) {
|
|
|
1788
1790
|
if (!tool)
|
|
1789
1791
|
return { ok: false, error: "unknown_tool", message: `No tool named ${name}.` };
|
|
1790
1792
|
try {
|
|
1791
|
-
|
|
1793
|
+
if (!["workspace_context", "bootstrap_workspace"].includes(name))
|
|
1794
|
+
await restoreWorkspace(ctx);
|
|
1795
|
+
if (ctx.workspace && !["status", "workspace_context", "bootstrap_workspace", "seed_grader_config", "write_grader_config_artifact"].includes(name)) {
|
|
1796
|
+
if (["onboard", "write_local_config"].includes(name))
|
|
1797
|
+
throw new Error("Use bootstrap_workspace to configure this persistent workspace and its scoped client profile.");
|
|
1798
|
+
if (["authenticate", "auth_status", "get_ingest_key"].includes(name))
|
|
1799
|
+
throw new Error("A persistent workspace is selected. Use bootstrap_workspace to reconnect or workspace_context to select another context.");
|
|
1800
|
+
const verified = await verifyScope({ key: ctx.session.useKey(), connectivityUrl: endpointsFor(ctx).connectivityUrl, expected: ctx.workspace.scope, fetchImpl: ctx.fetchImpl });
|
|
1801
|
+
if (!["scope_verified", "budget_exhausted"].includes(verified.state))
|
|
1802
|
+
throw new Error(`Workspace verification failed: ${verified.state}.`);
|
|
1803
|
+
}
|
|
1804
|
+
const delegate = ctx.workspace && !["workspace_context", "bootstrap_workspace"].includes(name) ? { ...ctx, fetchImpl: (async (url, init) => {
|
|
1805
|
+
const headers = new Headers(init?.headers);
|
|
1806
|
+
if (new URL(String(url)).origin === ctx.workspace.apiBase)
|
|
1807
|
+
headers.set("x-codetelemetry-workspace", JSON.stringify(ctx.workspace.scope));
|
|
1808
|
+
return (ctx.fetchImpl ?? fetch)(url, { ...init, headers });
|
|
1809
|
+
}) } : ctx;
|
|
1810
|
+
if (ctx.workspaceClient && ["status", "onboard", "write_local_config"].includes(name) && args.client === undefined)
|
|
1811
|
+
args = { ...args, client: ctx.workspaceClient };
|
|
1812
|
+
const result = await tool.handler(args ?? {}, delegate);
|
|
1813
|
+
if (name === "status")
|
|
1814
|
+
result.workspace = ctx.workspace ?? null;
|
|
1792
1815
|
return JSON.parse(scrub(JSON.stringify(result)));
|
|
1793
1816
|
}
|
|
1794
1817
|
catch (err) {
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const MCP_SERVER_NAME = "codetelemetry";
|
|
2
|
-
export declare const MCP_SERVER_VERSION = "0.
|
|
2
|
+
export declare const MCP_SERVER_VERSION = "0.4.1";
|
package/dist/src/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export const MCP_SERVER_NAME = "codetelemetry";
|
|
2
|
-
export const MCP_SERVER_VERSION = "0.
|
|
2
|
+
export const MCP_SERVER_VERSION = "0.4.1";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type WorkspaceContext } from "./client/workspaces.ts";
|
|
2
|
+
import type { ToolContext, ToolDef } from "./tools.ts";
|
|
3
|
+
export declare function activateWorkspace(ctx: ToolContext, context: WorkspaceContext): Promise<void>;
|
|
4
|
+
export declare function restoreWorkspace(ctx: ToolContext): Promise<void>;
|
|
5
|
+
export declare const workspaceTools: ToolDef[];
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { bootstrapWorkspace, } from "./client/bootstrap.js";
|
|
2
|
+
import { bindingOf, bindWorkspace, findWorkspaceBinding, listWorkspaces, loadWorkspace, sameWorkspace, saveWorkspace, workspaceOrigin, } from "./client/workspaces.js";
|
|
3
|
+
import { verifyScope } from "./client/connectivity.js";
|
|
4
|
+
import { resolveEndpoints } from "./client/config.js";
|
|
5
|
+
export async function activateWorkspace(ctx, context) {
|
|
6
|
+
if (ctx.endpointsOverride?.apiBase &&
|
|
7
|
+
workspaceOrigin(ctx.endpointsOverride.apiBase) !== context.apiBase)
|
|
8
|
+
throw new Error("Workspace conflicts with the host's pinned service.");
|
|
9
|
+
const checked = await verifyScope({
|
|
10
|
+
key: context.ingestKey,
|
|
11
|
+
connectivityUrl: resolveEndpoints({ apiBase: context.apiBase })
|
|
12
|
+
.connectivityUrl,
|
|
13
|
+
expected: context.scope,
|
|
14
|
+
fetchImpl: ctx.fetchImpl,
|
|
15
|
+
});
|
|
16
|
+
if (!["scope_verified", "budget_exhausted"].includes(checked.state) ||
|
|
17
|
+
!checked.scope ||
|
|
18
|
+
!sameWorkspace({ ...context, scope: checked.scope }, context))
|
|
19
|
+
throw new Error(`Workspace credentials could not be verified: ${checked.state}. Run bootstrap_workspace to reconnect.`);
|
|
20
|
+
ctx.session.setKey(context.ingestKey, "workspace");
|
|
21
|
+
ctx.session.apiBase = context.apiBase;
|
|
22
|
+
ctx.session.ingestEndpoint = context.ingestEndpoint;
|
|
23
|
+
ctx.session.keyScope = context.scope;
|
|
24
|
+
ctx.session.keyExpectedScope = context.scope;
|
|
25
|
+
if (context.clientConfig) {
|
|
26
|
+
ctx.configPathsOverride = {
|
|
27
|
+
...ctx.configPathsOverride,
|
|
28
|
+
[context.clientConfig.client]: ctx.configPathsOverride?.[context.clientConfig.client] ??
|
|
29
|
+
context.clientConfig.path,
|
|
30
|
+
};
|
|
31
|
+
ctx.workspaceClient = context.clientConfig.client;
|
|
32
|
+
}
|
|
33
|
+
ctx.workspace = bindingOf(context);
|
|
34
|
+
ctx.workspaceInitialized = true;
|
|
35
|
+
}
|
|
36
|
+
export async function restoreWorkspace(ctx) {
|
|
37
|
+
if (ctx.workspaceInitialized)
|
|
38
|
+
return;
|
|
39
|
+
const binding = findWorkspaceBinding();
|
|
40
|
+
const name = process.env.CODETELEMETRY_WORKSPACE || binding?.name;
|
|
41
|
+
if (!name) {
|
|
42
|
+
ctx.workspaceInitialized = true;
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const context = loadWorkspace(name);
|
|
46
|
+
if (binding && !sameWorkspace(binding, context))
|
|
47
|
+
throw new Error("Repository and selected workspace disagree. Select the intended context explicitly.");
|
|
48
|
+
if (ctx.session.hasKey() && ctx.session.useKey() !== context.ingestKey)
|
|
49
|
+
throw new Error("Environment credential conflicts with the repository workspace.");
|
|
50
|
+
await activateWorkspace(ctx, context);
|
|
51
|
+
}
|
|
52
|
+
export const workspaceTools = [
|
|
53
|
+
{
|
|
54
|
+
name: "bootstrap_workspace",
|
|
55
|
+
title: "Create or resume a workspace setup",
|
|
56
|
+
description: "Create/select an organization and finish repository-scoped setup using a persistent named context. New workspace setups enable prompt and tool-content capture by default; pass enrich:false to opt out. Saved capture choices are preserved on resume. The first call returns one browser approval URL; later calls with the same name resume the saved plan, verify funding and ingestion, optionally save/publish selected Grader checks and write Terraform. No credits or seats are purchased. Pass organizationName to create or organizationId to select. Existing contexts need neither. Each call is bounded; pending steps are explicit. Secrets stay local; unrelated global configurations are unchanged.",
|
|
57
|
+
inputSchema: {
|
|
58
|
+
type: "object",
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
required: ["name"],
|
|
61
|
+
properties: {
|
|
62
|
+
name: { type: "string", pattern: "^[a-z][a-z0-9_-]{0,63}$" },
|
|
63
|
+
repositoryPath: { type: "string", maxLength: 4096 },
|
|
64
|
+
offset: { type: "integer", minimum: 0, maximum: 63 },
|
|
65
|
+
limit: { type: "integer", minimum: 1, maximum: 10 },
|
|
66
|
+
organizationName: { type: "string", minLength: 1, maxLength: 60 },
|
|
67
|
+
organizationId: { type: "string", maxLength: 128 },
|
|
68
|
+
client: { type: "string", enum: ["claude", "codex"] },
|
|
69
|
+
configPath: { type: "string", maxLength: 4096 },
|
|
70
|
+
features: { type: "string", maxLength: 4000 },
|
|
71
|
+
checks: { type: "array", maxItems: 30, items: { type: "object" } },
|
|
72
|
+
publish: { type: "boolean" },
|
|
73
|
+
terraform: { type: "boolean" },
|
|
74
|
+
githubRepository: { type: "string", maxLength: 200 },
|
|
75
|
+
reauthorize: {
|
|
76
|
+
type: "boolean",
|
|
77
|
+
description: "Replace an expired or revoked credential after fresh approval, preserving this exact account and organization.",
|
|
78
|
+
},
|
|
79
|
+
enrich: { type: "boolean", default: true, description: "Capture prompts and tool content for new workspace setups (default true). Set false to opt out. Existing saved choices are preserved." },
|
|
80
|
+
repositoryObservation: { type: "boolean" },
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
async handler(args, ctx) {
|
|
84
|
+
const result = await bootstrapWorkspace(args, {
|
|
85
|
+
apiBase: ctx.endpointsOverride?.apiBase,
|
|
86
|
+
fetchImpl: ctx.fetchImpl,
|
|
87
|
+
});
|
|
88
|
+
if (["ready", "repository_action_required"].includes(result.status))
|
|
89
|
+
await activateWorkspace(ctx, loadWorkspace(String(args.name)));
|
|
90
|
+
return result;
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
name: "workspace_context",
|
|
95
|
+
title: "Manage persistent workspace contexts",
|
|
96
|
+
description: "List, save or select a named CodeTelemetry workspace. Credentials stay in private local storage and survive MCP restarts. Repository bindings contain only verified account/organization metadata. Save the currently authenticated key, or use an existing context; repositoryPath binds that repository without changing global telemetry. A conflicting binding requires explicit removal before switching.",
|
|
97
|
+
inputSchema: {
|
|
98
|
+
type: "object",
|
|
99
|
+
additionalProperties: false,
|
|
100
|
+
required: ["action"],
|
|
101
|
+
properties: {
|
|
102
|
+
action: { type: "string", enum: ["list", "save", "use"] },
|
|
103
|
+
name: { type: "string", pattern: "^[a-z][a-z0-9_-]{0,63}$" },
|
|
104
|
+
repositoryPath: { type: "string", maxLength: 4096 },
|
|
105
|
+
offset: { type: "integer", minimum: 0, maximum: 63 },
|
|
106
|
+
limit: { type: "integer", minimum: 1, maximum: 10 },
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
async handler(args, ctx) {
|
|
110
|
+
if (Object.keys(args).some((key) => !["action", "name", "repositoryPath", "offset", "limit"].includes(key)))
|
|
111
|
+
throw new Error("Unknown workspace context option.");
|
|
112
|
+
if (args.action === "list") {
|
|
113
|
+
const offset = args.offset ?? 0, limit = args.limit ?? 10;
|
|
114
|
+
if (!Number.isSafeInteger(offset) ||
|
|
115
|
+
Number(offset) < 0 ||
|
|
116
|
+
Number(offset) > 63 ||
|
|
117
|
+
!Number.isSafeInteger(limit) ||
|
|
118
|
+
Number(limit) < 1 ||
|
|
119
|
+
Number(limit) > 10)
|
|
120
|
+
throw new Error("Use offset 0–63 and limit 1–10.");
|
|
121
|
+
const all = listWorkspaces(), contexts = [];
|
|
122
|
+
for (const context of all.slice(Number(offset), Number(offset) + Number(limit))) {
|
|
123
|
+
if (Buffer.byteLength(JSON.stringify({
|
|
124
|
+
contexts: [...contexts, context],
|
|
125
|
+
selected: ctx.workspace ?? null,
|
|
126
|
+
})) >
|
|
127
|
+
20 * 1024)
|
|
128
|
+
break;
|
|
129
|
+
contexts.push(context);
|
|
130
|
+
}
|
|
131
|
+
const next = Number(offset) + contexts.length;
|
|
132
|
+
return {
|
|
133
|
+
ok: true,
|
|
134
|
+
contexts,
|
|
135
|
+
selected: ctx.workspace ?? null,
|
|
136
|
+
total: all.length,
|
|
137
|
+
...(next < all.length ? { nextOffset: next } : {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
if (args.action !== "save" && args.action !== "use")
|
|
141
|
+
throw new Error("Choose list, save or use.");
|
|
142
|
+
const name = String(args.name ?? "");
|
|
143
|
+
let context;
|
|
144
|
+
if (args.action === "save") {
|
|
145
|
+
if (!ctx.session.hasKey())
|
|
146
|
+
throw new Error("Authenticate before saving a workspace.");
|
|
147
|
+
const apiBase = workspaceOrigin(ctx.session.apiBase ??
|
|
148
|
+
ctx.endpointsOverride?.apiBase ??
|
|
149
|
+
resolveEndpoints().apiBase);
|
|
150
|
+
const verified = await verifyScope({
|
|
151
|
+
key: ctx.session.useKey(),
|
|
152
|
+
connectivityUrl: resolveEndpoints({ apiBase }).connectivityUrl,
|
|
153
|
+
expected: ctx.session.keyExpectedScope ?? {},
|
|
154
|
+
fetchImpl: ctx.fetchImpl,
|
|
155
|
+
});
|
|
156
|
+
if (!["scope_verified", "budget_exhausted"].includes(verified.state) ||
|
|
157
|
+
!verified.scope)
|
|
158
|
+
throw new Error(`Workspace verification failed: ${verified.state}.`);
|
|
159
|
+
context = {
|
|
160
|
+
version: 1,
|
|
161
|
+
name,
|
|
162
|
+
apiBase,
|
|
163
|
+
scope: verified.scope,
|
|
164
|
+
ingestEndpoint: ctx.session.ingestEndpoint ?? resolveEndpoints().ingestEndpoint,
|
|
165
|
+
ingestKey: ctx.session.useKey(),
|
|
166
|
+
};
|
|
167
|
+
saveWorkspace(context);
|
|
168
|
+
}
|
|
169
|
+
else
|
|
170
|
+
context = loadWorkspace(name);
|
|
171
|
+
if (args.repositoryPath !== undefined) {
|
|
172
|
+
const existing = findWorkspaceBinding(String(args.repositoryPath));
|
|
173
|
+
if (existing && !sameWorkspace(existing, context))
|
|
174
|
+
throw new Error("Repository is bound to another workspace.");
|
|
175
|
+
}
|
|
176
|
+
await activateWorkspace(ctx, context);
|
|
177
|
+
const bindingPath = args.repositoryPath === undefined
|
|
178
|
+
? undefined
|
|
179
|
+
: bindWorkspace(String(args.repositoryPath), context);
|
|
180
|
+
return {
|
|
181
|
+
ok: true,
|
|
182
|
+
workspace: bindingOf(context),
|
|
183
|
+
...(bindingPath ? { bindingPath } : {}),
|
|
184
|
+
};
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
];
|