@codetelemetry/mcp 0.4.1 → 0.6.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 +70 -3
- package/dist/src/client/bootstrap.d.ts +1 -0
- package/dist/src/client/bootstrap.js +6 -1
- package/dist/src/client/cli.js +57 -2
- package/dist/src/client/import/core.d.ts +8 -0
- package/dist/src/client/import/run.d.ts +3 -0
- package/dist/src/client/import/run.js +37 -7
- package/dist/src/client/import/sources/files.d.ts +18 -3
- package/dist/src/client/import/sources/files.js +108 -14
- package/dist/src/client/join.d.ts +35 -0
- package/dist/src/client/join.js +99 -0
- package/dist/src/client/otlp.d.ts +8 -1
- package/dist/src/client/otlp.js +4 -2
- package/dist/src/client/workspaceImport.d.ts +9 -0
- package/dist/src/client/workspaceImport.js +56 -0
- package/dist/src/client/workspaces.d.ts +3 -3
- package/dist/src/client/workspaces.js +55 -13
- package/dist/src/mcpServer.js +1 -1
- package/dist/src/tools.d.ts +1 -1
- package/dist/src/tools.js +62 -4
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -1
- package/tool-manifest.json +172 -6
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { bootstrapWorkspace } from "./bootstrap.js";
|
|
6
|
+
import { contextPath, findWorkspaceBinding, loadWorkspace, readWorkspaceFile, sameWorkspace, workspaceHome, workspaceOrigin } from "./workspaces.js";
|
|
7
|
+
export function joinPlan(options) {
|
|
8
|
+
if (!/^tm_[a-zA-Z0-9_-]{1,128}$/.test(options.organizationId))
|
|
9
|
+
throw new Error("Choose a valid existing organization ID.");
|
|
10
|
+
if (options.client !== "claude" && options.client !== "codex")
|
|
11
|
+
throw new Error("Choose Claude Code or Codex.");
|
|
12
|
+
const repositoryPath = fs.realpathSync(options.repositoryPath ?? process.cwd());
|
|
13
|
+
if (!fs.statSync(repositoryPath).isDirectory() || repositoryPath === os.homedir() || repositoryPath === path.parse(repositoryPath).root)
|
|
14
|
+
throw new Error("Choose a project directory, rather than your home or filesystem root.");
|
|
15
|
+
const binding = findWorkspaceBinding(repositoryPath);
|
|
16
|
+
if (binding && (binding.scope.teamId !== options.organizationId ||
|
|
17
|
+
(options.apiBase && binding.apiBase !== workspaceOrigin(options.apiBase))))
|
|
18
|
+
throw new Error("This project is connected to another destination; its connection was preserved.");
|
|
19
|
+
const digest = createHash("sha256").update(JSON.stringify([options.organizationId, repositoryPath, options.client])).digest("hex").slice(0, 12);
|
|
20
|
+
const slug = path.basename(repositoryPath).toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, 36) || "project";
|
|
21
|
+
let name = `project-${slug}-${digest}`;
|
|
22
|
+
if (binding) {
|
|
23
|
+
const context = loadWorkspace(binding.name);
|
|
24
|
+
if (context.clientConfig?.client === options.client)
|
|
25
|
+
name = binding.name;
|
|
26
|
+
}
|
|
27
|
+
const selected = findWorkspaceBinding(repositoryPath, name);
|
|
28
|
+
if (selected?.name === name) {
|
|
29
|
+
const saved = loadWorkspace(name);
|
|
30
|
+
if (!sameWorkspace(saved, selected))
|
|
31
|
+
throw new Error("The project's saved destination has changed.");
|
|
32
|
+
}
|
|
33
|
+
const checkpoint = path.join(workspaceHome(), `${name}.bootstrap.json`);
|
|
34
|
+
if (fs.existsSync(checkpoint)) {
|
|
35
|
+
const saved = readWorkspaceFile(checkpoint);
|
|
36
|
+
if (saved.plan?.repositoryPath !== repositoryPath || saved.plan?.client !== options.client ||
|
|
37
|
+
(saved.plan.organizationId && saved.plan.organizationId !== options.organizationId))
|
|
38
|
+
throw new Error("The saved connection does not match this project and coding tool.");
|
|
39
|
+
if (options.enrich !== undefined && saved.plan.enrich !== options.enrich)
|
|
40
|
+
throw new Error("This connection has a saved capture choice. Resume without a capture flag to preserve it.");
|
|
41
|
+
return { name, ...(options.reauthorize ? { reauthorize: true } : {}) };
|
|
42
|
+
}
|
|
43
|
+
if (fs.existsSync(contextPath(name)) && loadWorkspace(name).scope.teamId !== options.organizationId)
|
|
44
|
+
throw new Error("Saved connection belongs to another organization.");
|
|
45
|
+
return { name, organizationId: options.organizationId, repositoryPath, client: options.client,
|
|
46
|
+
repositoryObservation: true, ...(options.enrich === undefined ? {} : { enrich: options.enrich }),
|
|
47
|
+
...(options.reauthorize ? { reauthorize: true } : {}) };
|
|
48
|
+
}
|
|
49
|
+
export function workspaceProject(context) {
|
|
50
|
+
const checkpoint = path.join(workspaceHome(), `${context.name}.bootstrap.json`);
|
|
51
|
+
const state = readWorkspaceFile(checkpoint);
|
|
52
|
+
if (typeof state.plan?.repositoryPath !== "string")
|
|
53
|
+
throw new Error("This workspace has no saved project; connect it with join first.");
|
|
54
|
+
const project = fs.realpathSync(state.plan.repositoryPath);
|
|
55
|
+
const binding = findWorkspaceBinding(project, context.name);
|
|
56
|
+
if (!binding || !sameWorkspace(binding, context))
|
|
57
|
+
throw new Error("The saved project binding differs from this workspace.");
|
|
58
|
+
return project;
|
|
59
|
+
}
|
|
60
|
+
export async function joinOrganization(options, environment = {}) {
|
|
61
|
+
let plan = joinPlan(options);
|
|
62
|
+
const deadline = Date.now() + Math.min(600_000, environment.timeoutMs ?? 600_000);
|
|
63
|
+
const since = Date.now();
|
|
64
|
+
let opened = "";
|
|
65
|
+
let lastState = "";
|
|
66
|
+
while (true) {
|
|
67
|
+
const result = await bootstrapWorkspace(plan, { apiBase: options.apiBase, fetchImpl: environment.fetchImpl, connectionOnly: true,
|
|
68
|
+
timeoutMs: Math.min(45_000, Math.max(1, deadline - Date.now())) });
|
|
69
|
+
plan = { name: plan.name };
|
|
70
|
+
const authorizationUrl = result.authorizationUrl;
|
|
71
|
+
if (authorizationUrl && authorizationUrl !== opened) {
|
|
72
|
+
opened = authorizationUrl;
|
|
73
|
+
environment.log?.(`Approve your connection to ${options.organizationId}:\n${authorizationUrl}`);
|
|
74
|
+
environment.open?.(authorizationUrl);
|
|
75
|
+
}
|
|
76
|
+
if (result.status !== lastState) {
|
|
77
|
+
lastState = result.status;
|
|
78
|
+
if (result.status.startsWith("authorization_"))
|
|
79
|
+
environment.log?.("Waiting for browser approval. You can interrupt and run the same join command to resume.");
|
|
80
|
+
else if (result.nextAction)
|
|
81
|
+
environment.log?.(result.nextAction);
|
|
82
|
+
}
|
|
83
|
+
if (result.status === "ready") {
|
|
84
|
+
const context = loadWorkspace(plan.name);
|
|
85
|
+
if (context.scope.teamId !== options.organizationId)
|
|
86
|
+
throw new Error("Connected destination differs from the requested organization.");
|
|
87
|
+
const project = workspaceProject(context);
|
|
88
|
+
const progress = new URL(`/app/teams/${encodeURIComponent(options.organizationId)}/connect`, context.apiBase);
|
|
89
|
+
progress.search = new URLSearchParams({ client: options.client, project, workspace: context.name, since: String(since) }).toString();
|
|
90
|
+
environment.log?.(`Connection test received. Saved workspace: ${context.name}\n${result.steps.clientLaunch}\nRecord a real session to finish verification:\n${progress}`);
|
|
91
|
+
environment.open?.(String(progress));
|
|
92
|
+
return { ...result, progressUrl: String(progress), liveSessionVerified: false };
|
|
93
|
+
}
|
|
94
|
+
if (!environment.interactive || Date.now() >= deadline ||
|
|
95
|
+
!["authorization_required", "authorization_pending", "ingestion_pending"].includes(result.status))
|
|
96
|
+
return result;
|
|
97
|
+
await (environment.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(Math.min(5_000, Math.max(1, deadline - Date.now())));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -2,13 +2,20 @@ export type FetchLike = typeof fetch;
|
|
|
2
2
|
export declare const PROBE_ATTR = "codetelemetry.probe.id";
|
|
3
3
|
export declare const PROBE_EVENT = "codetelemetry_probe";
|
|
4
4
|
export declare const PROBE_SERVICE = "codetelemetry-connect";
|
|
5
|
-
export declare function buildProbeLog(probeId: string, nowMs?: number
|
|
5
|
+
export declare function buildProbeLog(probeId: string, nowMs?: number, context?: {
|
|
6
|
+
project: string;
|
|
7
|
+
client: "claude" | "codex";
|
|
8
|
+
}): unknown;
|
|
6
9
|
export type SendTestResult = {
|
|
7
10
|
probeId: string;
|
|
8
11
|
httpStatus: number;
|
|
9
12
|
ok: boolean;
|
|
10
13
|
};
|
|
11
14
|
export type SendTestOptions = {
|
|
15
|
+
context?: {
|
|
16
|
+
project: string;
|
|
17
|
+
client: "claude" | "codex";
|
|
18
|
+
};
|
|
12
19
|
key: string;
|
|
13
20
|
ingestEndpoint: string;
|
|
14
21
|
probeId?: string;
|
package/dist/src/client/otlp.js
CHANGED
|
@@ -3,7 +3,7 @@ import { assertKey } from "./keys.js";
|
|
|
3
3
|
export const PROBE_ATTR = "codetelemetry.probe.id";
|
|
4
4
|
export const PROBE_EVENT = "codetelemetry_probe";
|
|
5
5
|
export const PROBE_SERVICE = "codetelemetry-connect";
|
|
6
|
-
export function buildProbeLog(probeId, nowMs = Date.now()) {
|
|
6
|
+
export function buildProbeLog(probeId, nowMs = Date.now(), context) {
|
|
7
7
|
const nano = String(BigInt(Math.floor(nowMs)) * 1000000n);
|
|
8
8
|
return {
|
|
9
9
|
resourceLogs: [
|
|
@@ -11,6 +11,7 @@ export function buildProbeLog(probeId, nowMs = Date.now()) {
|
|
|
11
11
|
resource: {
|
|
12
12
|
attributes: [
|
|
13
13
|
{ key: "service.name", value: { stringValue: PROBE_SERVICE } },
|
|
14
|
+
...(context ? [{ key: "project.path", value: { stringValue: context.project } }] : []),
|
|
14
15
|
],
|
|
15
16
|
},
|
|
16
17
|
scopeLogs: [
|
|
@@ -26,6 +27,7 @@ export function buildProbeLog(probeId, nowMs = Date.now()) {
|
|
|
26
27
|
attributes: [
|
|
27
28
|
{ key: "event.name", value: { stringValue: PROBE_EVENT } },
|
|
28
29
|
{ key: PROBE_ATTR, value: { stringValue: probeId } },
|
|
30
|
+
...(context ? [{ key: "codetelemetry.probe.client", value: { stringValue: context.client } }] : []),
|
|
29
31
|
],
|
|
30
32
|
},
|
|
31
33
|
],
|
|
@@ -49,7 +51,7 @@ export async function sendTestEvent(opts) {
|
|
|
49
51
|
"content-type": "application/json",
|
|
50
52
|
authorization: `Bearer ${key}`,
|
|
51
53
|
},
|
|
52
|
-
body: JSON.stringify(buildProbeLog(probeId)),
|
|
54
|
+
body: JSON.stringify(buildProbeLog(probeId, Date.now(), opts.context)),
|
|
53
55
|
signal: ac.signal,
|
|
54
56
|
});
|
|
55
57
|
return { probeId, httpStatus: res.status, ok: res.status >= 200 && res.status < 300 };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ImportRunOptions } from "./import/run.ts";
|
|
2
|
+
import type { ImportRunResult } from "./import/core.ts";
|
|
3
|
+
export declare function importWorkspaceHistory(options: {
|
|
4
|
+
name: string;
|
|
5
|
+
preview?: boolean;
|
|
6
|
+
confirm?: boolean;
|
|
7
|
+
selections?: number[];
|
|
8
|
+
sinceMs?: number;
|
|
9
|
+
}, deps?: Pick<ImportRunOptions, "fetchImpl" | "claudeDir" | "codexDir" | "ledgerPath" | "nowMs" | "sleep">): Promise<ImportRunResult>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { loadWorkspace, workspaceHome, writeWorkspaceFile, readWorkspaceFile, workspaceCaptureDefault } from "./workspaces.js";
|
|
3
|
+
import { workspaceProject } from "./join.js";
|
|
4
|
+
import { keyHash } from "./keys.js";
|
|
5
|
+
import { verifyScope } from "./connectivity.js";
|
|
6
|
+
import { resolveEndpoints } from "./config.js";
|
|
7
|
+
import { runImport } from "./import/run.js";
|
|
8
|
+
import { sessionKeyOf } from "./import/model.js";
|
|
9
|
+
export async function importWorkspaceHistory(options, deps = {}) {
|
|
10
|
+
const context = loadWorkspace(options.name);
|
|
11
|
+
if (!context.scope.teamId || !context.clientConfig)
|
|
12
|
+
throw new Error("Choose a connected organization workspace.");
|
|
13
|
+
const project = workspaceProject(context);
|
|
14
|
+
const endpoints = { apiBase: context.apiBase, ingestEndpoint: context.ingestEndpoint };
|
|
15
|
+
const expected = context.scope;
|
|
16
|
+
const previewFile = path.join(workspaceHome(), `${context.name}.import-preview.json`);
|
|
17
|
+
const source = context.clientConfig.client === "claude" ? "claude-code" : "codex";
|
|
18
|
+
if (options.preview) {
|
|
19
|
+
if (options.confirm || options.selections)
|
|
20
|
+
throw new Error("Preview and import confirmation are separate actions.");
|
|
21
|
+
const capture = workspaceCaptureDefault(context);
|
|
22
|
+
const content = { prompts: capture, toolDetails: capture };
|
|
23
|
+
const result = await runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
|
|
24
|
+
sinceMs: options.sinceMs, content: { "claude-code": content, codex: content }, previewOnly: true });
|
|
25
|
+
const preview = { version: 1, workspace: context.name, keyHash: keyHash(context.ingestKey),
|
|
26
|
+
project, createdAt: Date.now(), scope: expected, window: result.window, content: result.content,
|
|
27
|
+
sessions: result.previewSessions ?? [] };
|
|
28
|
+
writeWorkspaceFile(previewFile, preview);
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
if (!options.confirm || !options.selections?.length || options.selections.length > 100 ||
|
|
32
|
+
options.sinceMs !== undefined)
|
|
33
|
+
throw new Error("Preview first, then use --select 1,2,… --confirm to import only those sessions.");
|
|
34
|
+
const preview = readWorkspaceFile(previewFile);
|
|
35
|
+
if (preview.version !== 1 || preview.workspace !== context.name || preview.keyHash !== keyHash(context.ingestKey) ||
|
|
36
|
+
preview.project !== project || JSON.stringify(preview.scope) !== JSON.stringify(expected) ||
|
|
37
|
+
!Number.isFinite(preview.createdAt) || Date.now() - preview.createdAt > 24 * 60 * 60_000 ||
|
|
38
|
+
!Array.isArray(preview.sessions) || preview.sessions.length > 100)
|
|
39
|
+
throw new Error("The preview expired or its destination changed. Preview again.");
|
|
40
|
+
const selectedPlans = Object.create(null);
|
|
41
|
+
for (const index of options.selections) {
|
|
42
|
+
if (!Number.isInteger(index) || index < 1 || index > preview.sessions.length)
|
|
43
|
+
throw new Error("Choose session numbers from the latest preview.");
|
|
44
|
+
const item = preview.sessions[index - 1];
|
|
45
|
+
if ((item.source !== "codex" && item.source !== "claude-code") || typeof item.sessionId !== "string" || item.sessionId.length > 512 || !/^[a-f0-9]{32}$/.test(item.planId))
|
|
46
|
+
throw new Error("Invalid preview; generate it again.");
|
|
47
|
+
selectedPlans[sessionKeyOf(item.source, item.sessionId)] = item.planId;
|
|
48
|
+
}
|
|
49
|
+
const verified = await verifyScope({ key: context.ingestKey, expected,
|
|
50
|
+
connectivityUrl: resolveEndpoints(endpoints).connectivityUrl, fetchImpl: deps.fetchImpl });
|
|
51
|
+
if (verified.state !== "scope_verified")
|
|
52
|
+
throw new Error(`Workspace is unavailable: ${verified.state}. No history was uploaded.`);
|
|
53
|
+
return runImport({ ...deps, key: context.ingestKey, endpoints, project, source,
|
|
54
|
+
sinceMs: Date.parse(preview.window.sinceIso), untilMs: Date.parse(preview.window.untilIso),
|
|
55
|
+
content: preview.content, selectedPlans, maxSessions: 100, timeLimitMs: 120_000 });
|
|
56
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { KeyScope } from "./connectivity.ts";
|
|
2
|
-
export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.
|
|
2
|
+
export declare const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.6.0";
|
|
3
3
|
export declare const MAX_WORKSPACE_BYTES: number;
|
|
4
4
|
export declare const MAX_WORKSPACES = 64;
|
|
5
5
|
export type WorkspaceBinding = {
|
|
@@ -41,5 +41,5 @@ export declare function contextPath(name: string): string;
|
|
|
41
41
|
export declare function loadWorkspace(name: string): WorkspaceContext;
|
|
42
42
|
export declare function saveWorkspace(context: WorkspaceContext): void;
|
|
43
43
|
export declare function listWorkspaces(): WorkspaceBinding[];
|
|
44
|
-
export declare function findWorkspaceBinding(start?: string): WorkspaceBinding | null;
|
|
45
|
-
export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding): string;
|
|
44
|
+
export declare function findWorkspaceBinding(start?: string, selectedName?: string | undefined): WorkspaceBinding | null;
|
|
45
|
+
export declare function bindWorkspace(repositoryPath: string, context: WorkspaceBinding, client?: "claude" | "codex"): string;
|
|
@@ -3,16 +3,19 @@ import os from "node:os";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { createHash, randomBytes } from "node:crypto";
|
|
5
5
|
import { buildOtelSection } from "./codexConfig.js";
|
|
6
|
-
import { repositoryHookSource, quotedCommand, REPOSITORY_HOOK_FILE } from "./repositoryHook.js";
|
|
6
|
+
import { repositoryHookSource, quotedCommand, REPOSITORY_HOOK_FILE, REPOSITORY_HOOK_STATE_FILE } from "./repositoryHook.js";
|
|
7
7
|
import { looksLikeKey } from "./keys.js";
|
|
8
|
-
export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.
|
|
8
|
+
export const WORKSPACE_MCP_PACKAGE = "@codetelemetry/mcp@0.6.0";
|
|
9
9
|
export const MAX_WORKSPACE_BYTES = 64 * 1024;
|
|
10
10
|
export const MAX_WORKSPACES = 64;
|
|
11
|
+
const isContextFile = (name) => /^[a-z][a-z0-9_-]{0,63}\.json$/.test(name) && name !== REPOSITORY_HOOK_STATE_FILE;
|
|
11
12
|
export function workspaceName(value) {
|
|
12
13
|
if (typeof value !== "string" ||
|
|
13
14
|
looksLikeKey(value) ||
|
|
14
15
|
!/^[a-z][a-z0-9_-]{0,63}$/.test(value))
|
|
15
16
|
throw new Error("Workspace name must be 1–64 lowercase letters, digits, underscores or hyphens, starting with a letter.");
|
|
17
|
+
if (`${value}.json` === REPOSITORY_HOOK_STATE_FILE)
|
|
18
|
+
throw new Error("Workspace name is reserved for repository-hook state.");
|
|
16
19
|
return value;
|
|
17
20
|
}
|
|
18
21
|
export function workspaceOrigin(value) {
|
|
@@ -334,7 +337,7 @@ export function saveWorkspace(context) {
|
|
|
334
337
|
fs.mkdirSync(workspaceHome(), { recursive: true, mode: 0o700 });
|
|
335
338
|
noLinks(workspaceHome());
|
|
336
339
|
if (!fs.existsSync(file) &&
|
|
337
|
-
workspaceEntries().filter(
|
|
340
|
+
workspaceEntries().filter(isContextFile)
|
|
338
341
|
.length >= MAX_WORKSPACES)
|
|
339
342
|
throw new Error("Workspace store is full; remove unused contexts before continuing.");
|
|
340
343
|
writeWorkspaceFile(file, checked);
|
|
@@ -350,35 +353,74 @@ export function listWorkspaces() {
|
|
|
350
353
|
const names = workspaceEntries();
|
|
351
354
|
if (names.length > MAX_WORKSPACES * 3)
|
|
352
355
|
throw new Error("Workspace store exceeds its entry bound.");
|
|
353
|
-
const files = names.filter(
|
|
356
|
+
const files = names.filter(isContextFile);
|
|
354
357
|
if (files.length > MAX_WORKSPACES)
|
|
355
358
|
throw new Error("Workspace store exceeds 64 contexts.");
|
|
356
359
|
return files
|
|
357
360
|
.sort()
|
|
358
361
|
.map((file) => bindingOf(loadWorkspace(file.slice(0, -5))));
|
|
359
362
|
}
|
|
360
|
-
export function findWorkspaceBinding(start = process.cwd()) {
|
|
363
|
+
export function findWorkspaceBinding(start = process.cwd(), selectedName = process.env.CODETELEMETRY_WORKSPACE) {
|
|
361
364
|
let dir = path.resolve(start);
|
|
362
365
|
for (let depth = 0; depth < 64; depth++) {
|
|
363
366
|
const file = path.join(dir, ".codetelemetry", "workspace.json");
|
|
364
|
-
if (fs.existsSync(file))
|
|
365
|
-
|
|
367
|
+
if (fs.existsSync(file)) {
|
|
368
|
+
const raw = readWorkspaceFile(file, false);
|
|
369
|
+
const primary = bindingOf(raw);
|
|
370
|
+
if (selectedName && primary.name !== selectedName) {
|
|
371
|
+
const clients = raw.clientBindings;
|
|
372
|
+
if (clients && typeof clients === "object" && !Array.isArray(clients)) {
|
|
373
|
+
for (const client of ["claude", "codex"]) {
|
|
374
|
+
if (clients[client]) {
|
|
375
|
+
const candidate = bindingOf(clients[client]);
|
|
376
|
+
if (candidate.name === selectedName)
|
|
377
|
+
return candidate;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return primary;
|
|
383
|
+
}
|
|
366
384
|
if (fs.existsSync(path.join(dir, ".git")) || path.dirname(dir) === dir)
|
|
367
385
|
return null;
|
|
368
386
|
dir = path.dirname(dir);
|
|
369
387
|
}
|
|
370
388
|
throw new Error("Workspace binding search exceeded 64 parents.");
|
|
371
389
|
}
|
|
372
|
-
export function bindWorkspace(repositoryPath, context) {
|
|
390
|
+
export function bindWorkspace(repositoryPath, context, client) {
|
|
373
391
|
const root = fs.realpathSync(repositoryPath);
|
|
374
392
|
if (!fs.statSync(root).isDirectory() ||
|
|
375
393
|
root === os.homedir() ||
|
|
376
394
|
root === path.parse(root).root)
|
|
377
395
|
throw new Error("Choose a repository directory.");
|
|
378
396
|
const file = path.join(root, ".codetelemetry", "workspace.json");
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
397
|
+
noLinks(file);
|
|
398
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
399
|
+
const releaseBinding = workspaceLock(".store");
|
|
400
|
+
try {
|
|
401
|
+
const existing = fs.existsSync(file) ? readWorkspaceFile(file, false) : null;
|
|
402
|
+
const primary = existing ? bindingOf(existing) : null;
|
|
403
|
+
const sameDestination = primary && primary.apiBase === context.apiBase &&
|
|
404
|
+
JSON.stringify(primary.scope) === JSON.stringify(context.scope);
|
|
405
|
+
const rawClients = existing?.clientBindings;
|
|
406
|
+
const clientBindings = {};
|
|
407
|
+
if (rawClients !== undefined) {
|
|
408
|
+
if (!rawClients || typeof rawClients !== "object" || Array.isArray(rawClients) ||
|
|
409
|
+
Object.keys(rawClients).some(key => key !== "claude" && key !== "codex"))
|
|
410
|
+
throw new Error("Invalid repository client bindings.");
|
|
411
|
+
for (const [key, value] of Object.entries(rawClients))
|
|
412
|
+
clientBindings[key] = bindingOf(value);
|
|
413
|
+
}
|
|
414
|
+
if (primary && !sameWorkspace(primary, context) && (!client || !sameDestination ||
|
|
415
|
+
(clientBindings[client] && !sameWorkspace(clientBindings[client], context))))
|
|
416
|
+
throw new Error("Repository is bound to another workspace; remove its binding explicitly before switching.");
|
|
417
|
+
if (client)
|
|
418
|
+
clientBindings[client] = bindingOf(context);
|
|
419
|
+
writeWorkspaceFile(file, { ...(primary ?? bindingOf(context)),
|
|
420
|
+
...(Object.keys(clientBindings).length ? { clientBindings } : {}) });
|
|
421
|
+
return file;
|
|
422
|
+
}
|
|
423
|
+
finally {
|
|
424
|
+
releaseBinding();
|
|
425
|
+
}
|
|
384
426
|
}
|
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 (["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))
|
|
33
|
+
if (["workspace_context", "bootstrap_workspace", "interpret_session", "read_session_events", "compare_sessions", "plan_next_session", "discover_grader_checks", "backtest_grader_checks", "get_grader_run", "save_grader_draft", "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/tools.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type WorkspaceBinding } from "./client/workspaces.ts";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { type FetchLike, type OnboardClient } from "./client/index.ts";
|
|
4
4
|
import { OnboardingSession } from "./session.ts";
|
package/dist/src/tools.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { workspaceTools, restoreWorkspace } from "./workspaceRuntime.js";
|
|
2
|
+
import { loadWorkspace } from "./client/workspaces.js";
|
|
3
|
+
import { workspaceProject } from "./client/join.js";
|
|
2
4
|
import fs from "node:fs";
|
|
3
5
|
import os from "node:os";
|
|
4
6
|
import path from "node:path";
|
|
@@ -419,19 +421,21 @@ const GRADER_CHECK_PROP = obj({
|
|
|
419
421
|
evidenceRequirement: { type: "string", enum: ["coverage_increase"] },
|
|
420
422
|
createdFromActivityId: { type: "string", maxLength: 512 },
|
|
421
423
|
components: { type: "array", minItems: 1, maxItems: 8, items: obj({ name: { type: "string", minLength: 1, maxLength: 120 }, matcherRule: GRADER_MATCHER_PROP, requireSuccess: { type: "boolean" } }, ["name", "matcherRule", "requireSuccess"]) },
|
|
422
|
-
linkage: { type: "string", enum: ["signadot"], description: "Links a three-component composite
|
|
424
|
+
linkage: { type: "string", enum: ["signadot"], description: "Links a three-component composite to recorded sandbox readiness, an exact routing key and declared endpoint, and a positive validation result. May be required before push after the final edit. Keep it when re-saving a check read from get_grader_config; dropping it leaves an unlinked composite." },
|
|
423
425
|
}, ["id", "name", "category", "weight", "satisfactionMode", "minimumOccurrences", "aggregationMode", "enabled"]);
|
|
424
426
|
function graderSchemaValid(value, schema) {
|
|
425
427
|
if (schema.enum && !schema.enum.includes(value))
|
|
426
428
|
return false;
|
|
427
429
|
if (schema.type === "string")
|
|
428
430
|
return typeof value === "string" && value.length >= (schema.minLength ?? 0) && value.length <= (schema.maxLength ?? Infinity) && (!schema.pattern || new RegExp(schema.pattern).test(value));
|
|
431
|
+
if (schema.type === "integer")
|
|
432
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= (schema.minimum ?? -Infinity) && value <= (schema.maximum ?? Infinity);
|
|
429
433
|
if (schema.type === "number")
|
|
430
434
|
return typeof value === "number" && Number.isFinite(value) && value >= (schema.minimum ?? -Infinity) && value <= (schema.maximum ?? Infinity);
|
|
431
435
|
if (schema.type === "boolean")
|
|
432
436
|
return typeof value === "boolean";
|
|
433
437
|
if (schema.type === "array")
|
|
434
|
-
return Array.isArray(value) && value.length >= (schema.minItems ?? 0) && value.length <= (schema.maxItems ?? Infinity) && value.every(item => graderSchemaValid(item, schema.items));
|
|
438
|
+
return Array.isArray(value) && value.length >= (schema.minItems ?? 0) && value.length <= (schema.maxItems ?? Infinity) && (!schema.uniqueItems || new Set(value).size === value.length) && value.every(item => graderSchemaValid(item, schema.items));
|
|
435
439
|
if (schema.type === "object") {
|
|
436
440
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
437
441
|
return false;
|
|
@@ -456,7 +460,7 @@ function graderMatcherValid(value) {
|
|
|
456
460
|
return Object.keys(node).length === 1 && visit(node.not, depth + 1);
|
|
457
461
|
if (++conditions > 64 || Object.keys(node).some(key => !["field", "operator", "value"].includes(key)))
|
|
458
462
|
return false;
|
|
459
|
-
if (!["source", "toolNamespace", "toolName", "operation", "executable", "packageScript", "packageScriptFamily", "normalizedArguments", "workingDirectory", "outcome", "exactFingerprint", "familyFingerprint"].includes(node.field) || !["equals", "in", "contains", "startsWith", "exists"].includes(node.operator))
|
|
463
|
+
if (!["source", "toolNamespace", "toolName", "operation", "executable", "packageScript", "packageScriptFamily", "normalizedArguments", "workingDirectory", "repositoryRelativeWorkingDirectory", "outcome", "exactFingerprint", "familyFingerprint"].includes(node.field) || !["equals", "in", "contains", "startsWith", "exists"].includes(node.operator))
|
|
460
464
|
return false;
|
|
461
465
|
if (node.operator === "exists")
|
|
462
466
|
return node.value === undefined;
|
|
@@ -472,7 +476,7 @@ function graderCheckValid(value) {
|
|
|
472
476
|
return false;
|
|
473
477
|
if (value.components?.some((part) => !part.matcherRule?.include || !graderMatcherValid(part.matcherRule)))
|
|
474
478
|
return false;
|
|
475
|
-
if (value.linkage !== undefined && (value.satisfactionMode !== "composite" || value.components?.length !== 3
|
|
479
|
+
if (value.linkage !== undefined && (value.satisfactionMode !== "composite" || value.components?.length !== 3))
|
|
476
480
|
return false;
|
|
477
481
|
return value.satisfactionMode === "composite" ? Boolean(value.components?.length) : Boolean(value.matcherRule?.include || value.detectorRule?.include);
|
|
478
482
|
}
|
|
@@ -515,7 +519,48 @@ async function requestGrader(ctx, operation, body) {
|
|
|
515
519
|
note: update ? "Saved the Grader draft. Use publish_grader_config with this revision to apply it to future scoring when the user wants publication. Existing published versions and scores are unchanged."
|
|
516
520
|
: "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." };
|
|
517
521
|
}
|
|
522
|
+
const GRADER_RUN_SELECTION = {
|
|
523
|
+
repository: { type: "string", minLength: 1, maxLength: 512, description: "Recorded repository label, as returned by search_sessions." },
|
|
524
|
+
features: { type: "string", minLength: 1, maxLength: 4000, description: "Grading focus, for example common tests and static analysis before pushing." },
|
|
525
|
+
days: { type: "integer", minimum: 1, maximum: 30, description: "History window; defaults to 30 days." },
|
|
526
|
+
cohort: { type: "string", enum: ["pull_requests", "substantive"], description: "Defaults to PR-producing sessions. substantive includes all sessions with observed work." },
|
|
527
|
+
};
|
|
528
|
+
const GRADER_RUN_ID = { type: "string", pattern: "^[a-f0-9-]{36}$" };
|
|
529
|
+
const GRADER_RUN_IDS = { type: "array", minItems: 1, maxItems: 30, uniqueItems: true, items: { type: "string", minLength: 1, maxLength: 128 } };
|
|
530
|
+
const GRADER_RUN_TOOLS = [
|
|
531
|
+
{ name: "discover_grader_checks", title: "Discover Grader checks from history", route: "discover", required: ["repository", "features"], properties: GRADER_RUN_SELECTION,
|
|
532
|
+
description: "Discover common validation checks for a recorded repository and grading focus. The service selects PR-producing sessions (default), scans bounded canonical history asynchronously and ranks exact normalized commands by distinct sessions. Returns a runId; poll get_grader_run for candidates, package scope, provenance, ambiguities and coverage. No local files or scripts. Partial evidence never proves an absence. Does not change the Grader." },
|
|
533
|
+
{ name: "backtest_grader_checks", title: "Backtest Grader checks", route: "backtest", required: [], properties: { ...GRADER_RUN_SELECTION, discoveryId: GRADER_RUN_ID, candidateIds: GRADER_RUN_IDS, draftRevision: { type: "string", pattern: "^[a-f0-9]{64}$" }, checkIds: GRADER_RUN_IDS },
|
|
534
|
+
description: "Start an asynchronous backtest using discoveryId plus candidateIds, or draftRevision plus checkIds and repository (optional days/cohort/features). Uses pinned recorded evidence and the live Grader evaluator. Poll get_grader_run for completion and after-last-edit/before-push timing separately, per-session evidence, unknown outcomes and coverage limits. Does not publish or rewrite historical scores." },
|
|
535
|
+
{ name: "get_grader_run", title: "Read Grader discovery or backtest progress", route: "runs", required: ["runId"], properties: { runId: GRADER_RUN_ID, cursor: { type: "string", minLength: 1, maxLength: 32 } },
|
|
536
|
+
description: "Poll a Grader run and follow returned cursors for bounded result pages. Returns progress, pinned window/cohort/evaluator, ranked candidates or check summaries and per-session evidence. Follow summaryCursor for remaining check summaries, or draftChecksCursor to discover saved check IDs/names for backtesting with the returned draftRevision. Runs expire after 24 hours. Report partial, unknown and stale evidence explicitly; do not treat missing telemetry as a failed check. Access is checked on every call." },
|
|
537
|
+
{ name: "save_grader_draft", title: "Save selected backtested Grader checks", route: "save-draft", required: ["backtestId", "candidateIds", "expectedRevision"], properties: { backtestId: GRADER_RUN_ID, candidateIds: GRADER_RUN_IDS, expectedRevision: { type: "string", pattern: "^[a-f0-9]{64}$" } },
|
|
538
|
+
description: "Save selected candidates from a completed backtest into the Grader draft, preserving unrelated checks. Use current draftRevision from get_grader_run, or read get_grader_config, for expectedRevision. Refuses changed revisions and unresolved package or operand ambiguities. Returns saved check IDs and a new draft revision. Requires Grader write permission. Does not publish, change enforcement or rewrite stored scores. Never automatically retry an uncertain save; read the draft first." },
|
|
539
|
+
];
|
|
540
|
+
async function requestGraderRun(ctx, route, args) {
|
|
541
|
+
if (!ctx.session.hasKey())
|
|
542
|
+
return NO_KEY;
|
|
543
|
+
try {
|
|
544
|
+
const result = await graderConfigRequest({ key: ctx.session.useKey(), url: `${endpointsFor(ctx).agentGraderUrl}/${route}`, body: args, fetchImpl: ctx.fetchImpl });
|
|
545
|
+
if (result.ok)
|
|
546
|
+
return { ...result.config, ok: true };
|
|
547
|
+
const uncertain = route === "save-draft" && (result.httpStatus >= 500 || result.httpStatus < 300);
|
|
548
|
+
return { ok: false, error: uncertain ? "save_uncertain" : result.error ?? (result.httpStatus === 404 ? "not_supported" : "grader_unavailable"), message: uncertain ? "Read get_grader_config before retrying; the draft save may have completed." : result.message ?? "The Grader run request failed." };
|
|
549
|
+
}
|
|
550
|
+
catch {
|
|
551
|
+
return { ok: false, error: route === "save-draft" ? "save_uncertain" : route === "runs" ? "grader_unavailable" : "start_uncertain", message: route === "save-draft" ? "Read get_grader_config before retrying; the draft save may have completed." : "The Grader request could not be confirmed. Do not automatically repeat a start request." };
|
|
552
|
+
}
|
|
553
|
+
}
|
|
518
554
|
export const TOOLS = [
|
|
555
|
+
...GRADER_RUN_TOOLS.map(tool => ({
|
|
556
|
+
name: tool.name, title: tool.title, description: tool.description,
|
|
557
|
+
inputSchema: obj(tool.properties, [...tool.required]),
|
|
558
|
+
async handler(args, ctx) {
|
|
559
|
+
if (!graderSchemaValid(args, obj(tool.properties, [...tool.required])))
|
|
560
|
+
return { ok: false, error: "bad_input", message: "Pass only the fields in this Grader tool's schema." };
|
|
561
|
+
return requestGraderRun(ctx, tool.route, args);
|
|
562
|
+
},
|
|
563
|
+
})),
|
|
519
564
|
...workspaceTools,
|
|
520
565
|
{
|
|
521
566
|
name: "authenticate",
|
|
@@ -1724,6 +1769,7 @@ export const TOOLS = [
|
|
|
1724
1769
|
"It reads ~/.claude/projects and ~/.codex/sessions on this machine and sends them through the normal ingest under the session's key, tagged as imported. " +
|
|
1725
1770
|
"ALWAYS call it first with dryRun true (the default) and show the user the summary — sessions, tokens, what is skipped and the content setting — then ask before calling again with dryRun false. " +
|
|
1726
1771
|
"Sessions already captured live or already imported are skipped; an interrupted import resumes. Each call sends at most maxSessions; while `remaining` > 0, call again. " +
|
|
1772
|
+
"A persistent workspace restricts imports to its bound project and coding client; it never falls back to a personal or machine-wide destination. " +
|
|
1727
1773
|
"Imported history has tokens, prompts and tool results but no per-request latency, retries, permission decisions or active time. " +
|
|
1728
1774
|
"content defaults to live: exactly the prompt / tool text the user's live exporters are configured to send (Claude OTEL_LOG_USER_PROMPTS / OTEL_LOG_TOOL_DETAILS, Codex log_user_prompt); none sends no text; all sends prompt text and tool inputs regardless — only with the user's explicit agreement.",
|
|
1729
1775
|
inputSchema: obj({
|
|
@@ -1770,6 +1816,7 @@ export const TOOLS = [
|
|
|
1770
1816
|
codexConfig: ctx.configPathsOverride?.codex ?? CLIENTS.codex.resolveConfigPath({}),
|
|
1771
1817
|
}),
|
|
1772
1818
|
dryRun: args.dryRun !== false,
|
|
1819
|
+
boundedDiscovery: Boolean(ctx.workspace),
|
|
1773
1820
|
maxSessions,
|
|
1774
1821
|
timeLimitMs: IMPORT_TIME_LIMIT_MS,
|
|
1775
1822
|
importTool: "mcp",
|
|
@@ -1809,6 +1856,17 @@ export async function callTool(name, args, ctx) {
|
|
|
1809
1856
|
}) } : ctx;
|
|
1810
1857
|
if (ctx.workspaceClient && ["status", "onboard", "write_local_config"].includes(name) && args.client === undefined)
|
|
1811
1858
|
args = { ...args, client: ctx.workspaceClient };
|
|
1859
|
+
if (ctx.workspace && name === "import_history") {
|
|
1860
|
+
const saved = loadWorkspace(ctx.workspace.name);
|
|
1861
|
+
const project = workspaceProject(saved);
|
|
1862
|
+
const selected = typeof args.project === "string" ? path.resolve(args.project) : project;
|
|
1863
|
+
if (selected !== project && !selected.startsWith(project + path.sep))
|
|
1864
|
+
throw new Error("History import must stay inside this workspace's selected project.");
|
|
1865
|
+
const source = saved.clientConfig?.client === "claude" ? "claude-code" : "codex";
|
|
1866
|
+
if (args.source !== undefined && args.source !== source)
|
|
1867
|
+
throw new Error("Choose the workspace for that coding client before importing its history.");
|
|
1868
|
+
args = { ...args, project: selected, source };
|
|
1869
|
+
}
|
|
1812
1870
|
const result = await tool.handler(args ?? {}, delegate);
|
|
1813
1871
|
if (name === "status")
|
|
1814
1872
|
result.workspace = ctx.workspace ?? null;
|
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.6.0";
|
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.6.0";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codetelemetry/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "CodeTelemetry MCP server \u2014 lets a coding agent onboard a user end to end: authenticate (device code), obtain an ingest key, write the Claude Code OTEL config, send a test event, and confirm telemetry landed \u2014 then search, read, interpret and compare the user's own coding sessions, plan the next one, and size tasks, plans and Linear issues from that history. The plaintext key never enters the model's context.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|