@imenam/mcp-dependabot-tracker 1.0.23 → 1.0.25

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.
Files changed (73) hide show
  1. package/README.md +187 -76
  2. package/dist/shared/schemas/agent-token.schema.d.ts +47 -0
  3. package/dist/shared/schemas/agent-token.schema.js +18 -0
  4. package/dist/shared/schemas/api.schema.d.ts +25 -23
  5. package/dist/shared/schemas/api.schema.js +8 -8
  6. package/dist/shared/schemas/deploy.schema.d.ts +174 -0
  7. package/dist/shared/schemas/deploy.schema.js +72 -0
  8. package/dist/shared/schemas/model.schema.d.ts +9 -26
  9. package/dist/shared/schemas/model.schema.js +7 -15
  10. package/dist/src/cli/setup-mcp.d.ts +19 -16
  11. package/dist/src/cli/setup-mcp.js +35 -82
  12. package/dist/src/cli/users.d.ts +5 -0
  13. package/dist/src/cli/users.js +164 -0
  14. package/dist/src/core/agent-tokens.d.ts +15 -0
  15. package/dist/src/core/agent-tokens.js +96 -0
  16. package/dist/src/core/auth.d.ts +774 -0
  17. package/dist/src/core/auth.js +191 -0
  18. package/dist/src/core/commands.d.ts +1 -1
  19. package/dist/src/core/commands.js +47 -4
  20. package/dist/src/core/config.d.ts +2 -1
  21. package/dist/src/core/config.js +1 -4
  22. package/dist/src/core/data-dir.d.ts +3 -1
  23. package/dist/src/core/data-dir.js +11 -5
  24. package/dist/src/core/deploy-servers.d.ts +77 -0
  25. package/dist/src/core/deploy-servers.js +480 -0
  26. package/dist/src/core/deployments.d.ts +75 -0
  27. package/dist/src/core/deployments.js +387 -0
  28. package/dist/src/core/github.d.ts +2 -0
  29. package/dist/src/core/github.js +8 -0
  30. package/dist/src/core/log-dir.d.ts +1 -5
  31. package/dist/src/core/log-dir.js +1 -5
  32. package/dist/src/core/npm-sandbox.d.ts +19 -3
  33. package/dist/src/core/npm-sandbox.js +87 -17
  34. package/dist/src/core/operations.d.ts +20 -18
  35. package/dist/src/core/operations.js +86 -70
  36. package/dist/src/core/repair.d.ts +0 -7
  37. package/dist/src/core/repair.js +10 -33
  38. package/dist/src/core/repos.d.ts +2 -3
  39. package/dist/src/core/repos.js +4 -7
  40. package/dist/src/core/server-config.d.ts +29 -0
  41. package/dist/src/core/server-config.js +85 -0
  42. package/dist/src/core/settings.d.ts +9 -3
  43. package/dist/src/core/settings.js +49 -10
  44. package/dist/src/core/ssh.d.ts +31 -0
  45. package/dist/src/core/ssh.js +82 -0
  46. package/dist/src/core/store.d.ts +5 -12
  47. package/dist/src/core/store.js +82 -160
  48. package/dist/src/core/vault.d.ts +10 -0
  49. package/dist/src/core/vault.js +50 -0
  50. package/dist/src/index.d.ts +9 -0
  51. package/dist/src/index.js +46 -455
  52. package/dist/src/mcp.d.ts +6 -0
  53. package/dist/src/mcp.js +59 -0
  54. package/dist/src/server/app.d.ts +47 -0
  55. package/dist/src/server/app.js +273 -0
  56. package/dist/src/server/serve.d.ts +7 -0
  57. package/dist/src/server/serve.js +178 -0
  58. package/dist/src/tools/client.d.ts +15 -0
  59. package/dist/src/tools/client.js +62 -0
  60. package/dist/src/tools/format.d.ts +4 -5
  61. package/dist/src/tools/format.js +39 -16
  62. package/dist/src/tools/tools.d.ts +101 -15
  63. package/dist/src/tools/tools.js +91 -62
  64. package/gui/dist/assets/index-FrRzRTkV.js +71 -0
  65. package/gui/dist/assets/index-o3l3BAZD.css +1 -0
  66. package/gui/dist/index.html +2 -2
  67. package/package.json +11 -4
  68. package/dist/shared/schemas/ipc.schema.d.ts +0 -26
  69. package/dist/shared/schemas/ipc.schema.js +0 -53
  70. package/dist/src/gui-worker.d.ts +0 -1
  71. package/dist/src/gui-worker.js +0 -379
  72. package/gui/dist/assets/index-CS33iXZk.css +0 -1
  73. package/gui/dist/assets/index-CZN3w6nU.js +0 -64
@@ -0,0 +1,50 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
2
+ import { TrackerError } from "./errors.js";
3
+ const KEY_BYTES = 32;
4
+ const IV_BYTES = 12;
5
+ const FORMAT_VERSION = "v1";
6
+ const GENERATE_HINT = "npx -y @imenam/mcp-dependabot-tracker --generate-vault-key";
7
+ /** Nouvelle clé de coffre : 32 octets aléatoires, en base64. */
8
+ export function generateVaultKey() {
9
+ return randomBytes(KEY_BYTES).toString("base64");
10
+ }
11
+ /** Décode VAULT_KEY ; lève une erreur qui dit comment en obtenir une valide. */
12
+ export function parseVaultKey(raw) {
13
+ const value = raw?.trim();
14
+ if (!value) {
15
+ throw new TrackerError(`VAULT_KEY is not set. It encrypts the SSH private keys of the deployment servers: generate one with \`${GENERATE_HINT}\` and set it as a secret variable of the server.`);
16
+ }
17
+ const key = Buffer.from(value, "base64");
18
+ if (key.length !== KEY_BYTES || key.toString("base64") !== value) {
19
+ throw new TrackerError(`VAULT_KEY is not a valid key: expected ${KEY_BYTES} bytes encoded in base64. Generate one with \`${GENERATE_HINT}\`.`);
20
+ }
21
+ return key;
22
+ }
23
+ /** Chiffre en AES-256-GCM : `v1:<iv>:<tag>:<chiffré>`, chaque partie en base64. */
24
+ export function encryptSecret(plaintext, key) {
25
+ const iv = randomBytes(IV_BYTES);
26
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
27
+ const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
28
+ const tag = cipher.getAuthTag();
29
+ return [FORMAT_VERSION, iv.toString("base64"), tag.toString("base64"), encrypted.toString("base64")].join(":");
30
+ }
31
+ /** Vrai pour une valeur au format de `encryptSecret`. */
32
+ export function isEncrypted(value) {
33
+ const parts = value.split(":");
34
+ return parts.length === 4 && parts[0] === FORMAT_VERSION;
35
+ }
36
+ /** Déchiffre un secret produit par `encryptSecret` ; échoue si la clé n'est pas la bonne. */
37
+ export function decryptSecret(payload, key) {
38
+ const parts = payload.split(":");
39
+ if (parts.length !== 4 || parts[0] !== FORMAT_VERSION)
40
+ throw new TrackerError("Encrypted value has an unknown format.");
41
+ const [, iv, tag, encrypted] = parts;
42
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64"));
43
+ decipher.setAuthTag(Buffer.from(tag, "base64"));
44
+ try {
45
+ return Buffer.concat([decipher.update(Buffer.from(encrypted, "base64")), decipher.final()]).toString("utf8");
46
+ }
47
+ catch {
48
+ throw new TrackerError("VAULT_KEY does not decrypt this value: it is not the key that was used to encrypt it.");
49
+ }
50
+ }
@@ -1,2 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ /**
3
+ * Point d'entrée du paquet :
4
+ * serve le serveur Dependabot Tracker (interface, API, opérations) ;
5
+ * mcp le mode MCP, lancé par un agent, qui pilote un serveur ;
6
+ * user add|password|totp|remove|list gère les comptes de l'interface ;
7
+ * --claude-setup-mcp --server_url=… --token=… déclare le mode MCP dans le .mcp.json du répertoire courant ;
8
+ * --generate-vault-key affiche une nouvelle VAULT_KEY ;
9
+ * --generate-auth-secret affiche un nouvel AUTH_SECRET.
10
+ */
2
11
  export {};
package/dist/src/index.js CHANGED
@@ -1,466 +1,57 @@
1
1
  #!/usr/bin/env node
2
- import dotenv from "dotenv";
3
- import path from "path";
4
- import fs from "fs";
5
- import { fileURLToPath } from "url";
6
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
- import { GuiLauncher, createLogger, reconnectGuiToolDefinition, setupLogging } from "@imenam/mcp-gui-interface";
10
- import { APP_VERSION } from "./version.js";
11
- import { resolveCloneDir, resolveDataDir } from "./core/data-dir.js";
12
- import { resolveLogDir } from "./core/log-dir.js";
13
- import { githubConfigured, readGitHubConfig } from "./core/config.js";
14
- import { ConflictError, NotFoundError, TrackerError } from "./core/errors.js";
15
- import { Store } from "./core/store.js";
16
- import { assertMergeAuditPossible, cancelOperation, runDefaultBranchAudit, startMergeAudit, startUserFix } from "./core/operations.js";
17
- import { AuditAll } from "./core/audit-all.js";
18
- import { refreshReportTask } from "./core/repair.js";
19
- import { checkClaudeToken, packagedClaudeCommand } from "./core/claude.js";
20
- import { OrganizerClient } from "./core/organizer.js";
21
- import { readSettings, saveSettings, settingsView, testOrganizer } from "./core/settings.js";
22
- import { SaveSettingsBodySchema } from "../shared/schemas/settings.schema.js";
23
- import { AUDIT_SCOPES } from "../shared/schemas/model.schema.js";
24
- import { SYNC_INTERVAL_MS, addRepository, auditTargetRepos, queueCategory, queueRepository, unqueueRepository, markDeployPending, unmarkDeployPending, markPullRequestsMerged, operationSummary, deprecateRepository, listAddableRepositories, restoreRepository, listRepoBranches, listRepoViews, markAlertHandled, setBranch, setCategory, repoView, setRights, staleRepos, syncAllRepositories, syncRepository, unmarkAlertHandled } from "./core/repos.js";
25
- import { GUI_REQUEST_TYPES, IPCMessageSchema } from "../shared/schemas/ipc.schema.js";
26
- import { AddRepoBodySchema, AlertRequestSchema, CategoryBodySchema, CategoryRequestSchema, MergedBodySchema, OperationRequestSchema, RepoRequestSchema, AuditAllBodySchema, ScopeBodySchema, SetBranchBodySchema, SetCategoryBodySchema, SetRightsBodySchema, } from "../shared/schemas/api.schema.js";
27
- import { errorResult, textResult } from "./tools/types.js";
28
- import { fixVulnerabilities, getAlerts, listRepositories, runAudit } from "./tools/tools.js";
29
- const __filename = fileURLToPath(import.meta.url);
30
- const __dirname = path.dirname(__filename);
31
- // Les flags CLI sont traités avant toute initialisation : ils s'exécutent dans le
32
- // répertoire de l'utilisateur, pas dans un serveur MCP.
33
- if (process.argv.slice(2).includes("--claude-setup-mcp")) {
34
- const argv = process.argv.slice(2);
35
- const { runSetupMcp, parseGuiExposure } = await import("./cli/setup-mcp.js");
36
- const parsed = parseGuiExposure(argv);
2
+ /**
3
+ * Point d'entrée du paquet :
4
+ * serve le serveur Dependabot Tracker (interface, API, opérations) ;
5
+ * mcp le mode MCP, lancé par un agent, qui pilote un serveur ;
6
+ * user add|password|totp|remove|list gère les comptes de l'interface ;
7
+ * --claude-setup-mcp --server_url=… --token=… déclare le mode MCP dans le .mcp.json du répertoire courant ;
8
+ * --generate-vault-key affiche une nouvelle VAULT_KEY ;
9
+ * --generate-auth-secret affiche un nouvel AUTH_SECRET.
10
+ */
11
+ const { USERS_USAGE } = await import("./cli/users.js");
12
+ const USAGE = [
13
+ "Usage :",
14
+ " mcp-dependabot-tracker serve lance le serveur",
15
+ " mcp-dependabot-tracker mcp mode MCP, lancé par un agent (SERVER_URL, AGENT_TOKEN)",
16
+ USERS_USAGE,
17
+ " mcp-dependabot-tracker --claude-setup-mcp --server_url=<url> --token=<token> [--force]",
18
+ " mcp-dependabot-tracker --generate-vault-key affiche une nouvelle VAULT_KEY",
19
+ " mcp-dependabot-tracker --generate-auth-secret affiche un nouvel AUTH_SECRET",
20
+ ].join("\n");
21
+ const argv = process.argv.slice(2);
22
+ if (argv.includes("--generate-vault-key")) {
23
+ const { generateVaultKey } = await import("./core/vault.js");
24
+ console.log(generateVaultKey());
25
+ }
26
+ else if (argv.includes("--generate-auth-secret")) {
27
+ const { generateAuthSecret } = await import("./core/auth.js");
28
+ console.log(generateAuthSecret());
29
+ }
30
+ else if (argv.includes("--claude-setup-mcp")) {
31
+ const { parseConnection, runSetupMcp } = await import("./cli/setup-mcp.js");
32
+ const parsed = parseConnection(argv);
37
33
  if ("error" in parsed) {
38
34
  console.error(`Erreur : ${parsed.error}`);
39
35
  process.exit(1);
40
36
  }
41
- process.exit(runSetupMcp({ cwd: process.cwd(), force: argv.includes("--force"), exposure: parsed.exposure }));
37
+ process.exit(runSetupMcp({ cwd: process.cwd(), force: argv.includes("--force"), connection: parsed.connection }));
42
38
  }
43
- function findProjectRoot(startDir) {
44
- let current = startDir;
45
- while (current !== path.dirname(current)) {
46
- if (fs.existsSync(path.join(current, "package.json")))
47
- return current;
48
- current = path.dirname(current);
49
- }
50
- return startDir;
39
+ else if (argv[0] === "serve") {
40
+ const { serve } = await import("./server/serve.js");
41
+ await serve();
51
42
  }
52
- const rootDir = findProjectRoot(__dirname);
53
- const packageEnvPath = path.join(rootDir, ".env");
54
- setupLogging({ processLabel: "mcp-dependabot-tracker", logDir: resolveLogDir() });
55
- const logger = createLogger("mcp-dependabot-tracker");
56
- // Rechargé à chaque appel, avec override : le .env local prime sur les
57
- // variables héritées de la déclaration du MCP.
58
- function getConfig() {
59
- if (fs.existsSync(packageEnvPath))
60
- dotenv.config({ path: packageEnvPath, override: true, quiet: true });
61
- return { proxyUrl: process.env.PROXY_URL, appPort: process.env.APP_PORT, version: APP_VERSION };
43
+ else if (argv[0] === "user") {
44
+ const { loadPackageEnv } = await import("./server/serve.js");
45
+ loadPackageEnv();
46
+ const { runUsers } = await import("./cli/users.js");
47
+ process.exit(await runUsers(argv.slice(1)));
62
48
  }
63
- getConfig();
64
- let cloneDir;
65
- try {
66
- cloneDir = resolveCloneDir();
49
+ else if (argv[0] === "mcp") {
50
+ const { runMcp } = await import("./mcp.js");
51
+ await runMcp();
67
52
  }
68
- catch (err) {
69
- logger.error(err.message);
70
- console.error(err.message);
53
+ else {
54
+ console.error(USAGE);
71
55
  process.exit(1);
72
56
  }
73
- const dataDir = resolveDataDir();
74
- const store = new Store(dataDir);
75
- /** Claude Code du paquet, configuré dans `<données>/claude`. */
76
- const claude = { command: packagedClaudeCommand(), home: path.join(dataDir, "claude") };
77
- const settingsChecks = {
78
- organizer: (connection) => new OrganizerClient(connection).space(),
79
- claudeToken: (token) => checkClaudeToken(claude, token),
80
- };
81
- const operations = {
82
- store,
83
- githubConfig: readGitHubConfig,
84
- cloneDir: resolveCloneDir,
85
- logError: (message) => logger.error(message),
86
- settings: () => readSettings(dataDir),
87
- claude,
88
- };
89
- /** Série « Auditer tout » de la GUI servie par ce processus. */
90
- const auditAll = new AuditAll((repoId, scope) => runDefaultBranchAudit(operations, repoId, scope), (message) => logger.error(message));
91
- /** Présentation du serveur transmise au client MCP : concepts, déroulé et règles. */
92
- const INSTRUCTIONS = `mcp-dependabot-tracker follows the Dependabot alerts of GitHub repositories and fixes their npm vulnerabilities. The user tracks repositories and decides what you may do on each of them in a web GUI; you act only through these tools, never with git or npm yourself.
93
-
94
- Concepts:
95
- - A **tracked repository** is a GitHub repository the user added in the GUI. Its open Dependabot alerts, and the pull requests the tracker opened that are not merged or closed yet, are read from GitHub and refreshed every 10 minutes.
96
- - A **deprecated repository** is one the user set aside in the GUI: it is neither synced nor audited, list_repositories leaves it out, and every tool refuses it until the user restores it.
97
- - **Rights**: for each repository, the user allows you to run npm audit (audit), npm audit fix (fix) and to push the fixes (push). A tool refuses an action you are not allowed to do; only the user can change the rights.
98
- - The **scope** of an audit is chosen at each launch: production (the default) runs npm audit and npm audit fix with --omit=dev, so the devDependencies are left out; all covers every dependency. Each Dependabot alert says whether its dependency is a runtime or a development one.
99
- - The **analysed branch** of a repository is chosen by the user in the GUI (the default branch unless changed). Dependabot alerts always describe the default branch; npm audit describes the analysed branch.
100
- - An **operation** runs in a temporary clone of the analysed branch, deleted at the end: npm audit in every directory that holds a package-lock.json, then npm audit fix with --package-lock-only and --ignore-scripts (lockfiles only, no install, no scripts), then a commit on a new branch fix/npm-audit-<date>-<time> and a pull request to the analysed branch.
101
-
102
- Workflow:
103
- 1. list_repositories to see the tracked repositories, their open alerts and your rights.
104
- 2. get_alerts for the detail of the alerts of one repository.
105
- 3. run_audit to see what npm audit reports, or fix_vulnerabilities to fix, on the production dependencies unless the user asks for all of them: without push, nothing leaves the temporary clone and the result shows what the fixes would change; with push, the fixes are pushed and the pull request is opened.
106
-
107
- Rules:
108
- - An operation runs until it ends; one operation at a time per repository.`;
109
- const server = new Server({ name: "mcp-dependabot-tracker", version: APP_VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
110
- // --- GUI ----------------------------------------------------------------------
111
- function broadcastToGUI(message) {
112
- const child = guiLauncher.getProcess();
113
- if (child?.connected) {
114
- try {
115
- child.send(message);
116
- }
117
- catch (err) {
118
- logger.error(`Failed to send IPC message: ${err.message}`);
119
- }
120
- }
121
- }
122
- function reply(msg, data) {
123
- broadcastToGUI({ type: `${msg.type}_RESPONSE`, correlationId: msg.correlationId, data, timestamp: new Date().toISOString() });
124
- }
125
- function replyError(msg, error, errorKind) {
126
- broadcastToGUI({ type: `${msg.type}_RESPONSE`, correlationId: msg.correlationId, error, errorKind, timestamp: new Date().toISOString() });
127
- }
128
- /** Données IPC d'une requête de la GUI, validées par `schema` ; une donnée invalide est une erreur de la requête. */
129
- function parseRequest(schema, data) {
130
- const parsed = schema.safeParse(data);
131
- if (!parsed.success) {
132
- const issues = parsed.error.issues.map((issue) => `${issue.path.map(String).join(".") || "(root)"} ${issue.message}`);
133
- throw new TrackerError(`Invalid request: ${issues.join("; ")}.`);
134
- }
135
- return parsed.data;
136
- }
137
- function errorKindOf(err) {
138
- if (err instanceof NotFoundError)
139
- return "not_found";
140
- if (err instanceof ConflictError)
141
- return "conflict";
142
- if (err instanceof TrackerError)
143
- return "invalid";
144
- return "internal";
145
- }
146
- /** Traite une requête de la GUI et renvoie ses données de réponse ; lève une erreur métier sinon. */
147
- async function handleGuiRequest(msg) {
148
- switch (msg.type) {
149
- case "GET_CONFIG":
150
- return { version: APP_VERSION, dataDir, githubConfigured: githubConfigured() };
151
- case "LIST_REPOS":
152
- return { repos: listRepoViews(store), categories: store.listCategories() };
153
- case "SYNC_REPOS":
154
- await syncAllRepositories(store, readGitHubConfig());
155
- return { repos: listRepoViews(store), categories: store.listCategories() };
156
- case "GET_AUDIT_ALL":
157
- return { auditAll: auditAll.status() };
158
- case "START_AUDIT_ALL": {
159
- readGitHubConfig();
160
- store.failOrphanedOperations();
161
- const { scope, target } = parseRequest(AuditAllBodySchema, msg.data?.body);
162
- return { auditAll: auditAll.start(auditTargetRepos(store, target).map((repo) => repo.id), scope, target) };
163
- }
164
- case "LIST_ADDABLE_REPOS":
165
- return { repositories: await listAddableRepositories(store, readGitHubConfig()) };
166
- case "GET_REPO": {
167
- store.failOrphanedOperations();
168
- return repoView(store, store.getRepo(parseRequest(RepoRequestSchema, msg.data).repoId));
169
- }
170
- case "ADD_REPO": {
171
- const body = parseRequest(AddRepoBodySchema, msg.data?.body);
172
- return repoView(store, await addRepository(store, readGitHubConfig(), body.repository, body.categoryId));
173
- }
174
- case "REMOVE_REPO":
175
- store.removeRepo(parseRequest(RepoRequestSchema, msg.data).repoId);
176
- return { removed: true };
177
- case "DEPRECATE_REPO":
178
- return repoView(store, deprecateRepository(store, parseRequest(RepoRequestSchema, msg.data).repoId));
179
- case "QUEUE_REPO":
180
- return repoView(store, queueRepository(store, parseRequest(RepoRequestSchema, msg.data).repoId));
181
- case "UNQUEUE_REPO":
182
- return repoView(store, unqueueRepository(store, parseRequest(RepoRequestSchema, msg.data).repoId));
183
- case "MARK_DEPLOY_PENDING":
184
- return repoView(store, markDeployPending(store, parseRequest(RepoRequestSchema, msg.data).repoId));
185
- case "UNMARK_DEPLOY_PENDING":
186
- return repoView(store, unmarkDeployPending(store, parseRequest(RepoRequestSchema, msg.data).repoId));
187
- case "MARK_PULL_REQUESTS_MERGED": {
188
- const { repoId } = parseRequest(RepoRequestSchema, msg.data);
189
- const { deploy } = parseRequest(MergedBodySchema, msg.data?.body);
190
- const merged = store.getRepo(repoId).pullRequests.map((pull) => pull.number);
191
- if (merged.length > 0)
192
- assertMergeAuditPossible(operations, repoId);
193
- const repo = markPullRequestsMerged(store, repoId, deploy);
194
- if (merged.length > 0)
195
- startMergeAudit(operations, repo.id, merged);
196
- return repoView(store, repo);
197
- }
198
- case "RESTORE_REPO":
199
- return repoView(store, await restoreRepository(store, readGitHubConfig(), parseRequest(RepoRequestSchema, msg.data).repoId));
200
- case "SET_RIGHTS": {
201
- const { repoId } = parseRequest(RepoRequestSchema, msg.data);
202
- const body = parseRequest(SetRightsBodySchema, msg.data?.body);
203
- return repoView(store, setRights(store, repoId, body.rights));
204
- }
205
- case "LIST_BRANCHES": {
206
- const { repoId } = parseRequest(RepoRequestSchema, msg.data);
207
- return { branches: await listRepoBranches(store, readGitHubConfig(), repoId) };
208
- }
209
- case "SET_BRANCH": {
210
- const { repoId } = parseRequest(RepoRequestSchema, msg.data);
211
- const body = parseRequest(SetBranchBodySchema, msg.data?.body);
212
- return repoView(store, await setBranch(store, readGitHubConfig(), repoId, body.branch));
213
- }
214
- case "SET_CATEGORY": {
215
- const { repoId } = parseRequest(RepoRequestSchema, msg.data);
216
- const body = parseRequest(SetCategoryBodySchema, msg.data?.body);
217
- return repoView(store, setCategory(store, repoId, body.categoryId));
218
- }
219
- case "MARK_ALERT_HANDLED": {
220
- const { repoId, number } = parseRequest(AlertRequestSchema, msg.data);
221
- return repoView(store, markAlertHandled(store, repoId, number));
222
- }
223
- case "UNMARK_ALERT_HANDLED": {
224
- const { repoId, number } = parseRequest(AlertRequestSchema, msg.data);
225
- return repoView(store, unmarkAlertHandled(store, repoId, number));
226
- }
227
- case "LIST_CATEGORIES":
228
- return { categories: store.listCategories() };
229
- case "CREATE_CATEGORY":
230
- return store.createCategory(parseRequest(CategoryBodySchema, msg.data?.body).name);
231
- case "RENAME_CATEGORY": {
232
- const { categoryId } = parseRequest(CategoryRequestSchema, msg.data);
233
- return store.renameCategory(categoryId, parseRequest(CategoryBodySchema, msg.data?.body).name);
234
- }
235
- case "QUEUE_CATEGORY":
236
- queueCategory(store, parseRequest(CategoryRequestSchema, msg.data).categoryId);
237
- return { repos: listRepoViews(store), categories: store.listCategories() };
238
- case "DELETE_CATEGORY":
239
- store.deleteCategory(parseRequest(CategoryRequestSchema, msg.data).categoryId);
240
- return { deleted: true };
241
- case "START_FIX":
242
- return { operation: startUserFix(operations, parseRequest(RepoRequestSchema, msg.data).repoId, parseRequest(ScopeBodySchema, msg.data?.body).scope) };
243
- case "LIST_OPERATIONS": {
244
- store.failOrphanedOperations();
245
- const repo = store.getRepo(parseRequest(RepoRequestSchema, msg.data).repoId);
246
- return { operations: store.listOperations(repo.id).map(operationSummary) };
247
- }
248
- case "GET_OPERATION": {
249
- store.failOrphanedOperations();
250
- return { operation: store.getOperation(parseRequest(OperationRequestSchema, msg.data).operationId) };
251
- }
252
- case "CANCEL_OPERATION":
253
- return { operation: cancelOperation(operations, parseRequest(OperationRequestSchema, msg.data).operationId) };
254
- case "GET_SETTINGS":
255
- return settingsView(readSettings(dataDir));
256
- case "SAVE_SETTINGS":
257
- return saveSettings(dataDir, parseRequest(SaveSettingsBodySchema, msg.data?.body), settingsChecks);
258
- case "TEST_ORGANIZER":
259
- return testOrganizer(dataDir, settingsChecks);
260
- default:
261
- throw new Error(`GUI request ${msg.type} has no handler.`);
262
- }
263
- }
264
- const GUI_REQUESTS = new Set(GUI_REQUEST_TYPES);
265
- /**
266
- * Messages du GUI worker. READY et ALREADY_RUNNING sont d'abord traités par
267
- * GuiLauncher (statut, URL), puis transmis ici.
268
- */
269
- function handleIPCMessage(raw) {
270
- const parsed = IPCMessageSchema.safeParse(raw);
271
- if (!parsed.success) {
272
- logger.warn(`Invalid IPC message ignored: ${parsed.error.message}`);
273
- return;
274
- }
275
- const msg = parsed.data;
276
- switch (msg.type) {
277
- case "READY":
278
- logger.info(`GUI ready at ${msg.data?.url}`);
279
- return;
280
- case "ALREADY_RUNNING":
281
- logger.info(`GUI already served by another instance at ${msg.data?.url}`);
282
- return;
283
- default:
284
- if (GUI_REQUESTS.has(msg.type)) {
285
- handleGuiRequest(msg).then((data) => reply(msg, data), (err) => {
286
- const kind = errorKindOf(err);
287
- if (kind === "internal")
288
- logger.error(`GUI request ${msg.type} failed: ${err?.stack ?? err}`);
289
- replyError(msg, err?.message ?? String(err), kind);
290
- });
291
- return;
292
- }
293
- logger.debug(`Unhandled IPC message type: ${msg.type}`);
294
- }
295
- }
296
- const guiLauncher = new GuiLauncher({
297
- guiPath: path.join(__dirname, "gui-worker.js"),
298
- maxRestarts: 0,
299
- onMessage: handleIPCMessage,
300
- reloadEnv: getConfig,
301
- });
302
- /** La GUI a besoin soit d'un proxy, soit d'un port local (mode standalone). */
303
- function guiIsConfigured() {
304
- return !!(process.env.PROXY_URL?.trim() || process.env.APP_PORT?.trim());
305
- }
306
- function launchGUI() {
307
- if (!guiIsConfigured()) {
308
- logger.info("[MASTER] Ni PROXY_URL ni APP_PORT défini — GUI désactivée.");
309
- return;
310
- }
311
- logger.info("Launching GUI worker...");
312
- guiLauncher.start();
313
- }
314
- /**
315
- * `reconnect_gui` : relance via GuiLauncher en mode proxy. En mode standalone,
316
- * GuiLauncher ne sait pas relancer le worker : l'outil décrit l'état et la
317
- * marche à suivre.
318
- */
319
- async function reconnectGui(args) {
320
- getConfig();
321
- const appPort = process.env.APP_PORT?.trim();
322
- if (process.env.PROXY_URL?.trim() || !appPort) {
323
- return { ...(await guiLauncher.handleReconnectTool({ force: args.force === true })) };
324
- }
325
- const child = guiLauncher.getProcess();
326
- const alive = !!child && child.exitCode === null && !child.killed;
327
- const url = guiLauncher.getUrl();
328
- if (alive && guiLauncher.getStatus() === "ready") {
329
- return textResult(`GUI is served in standalone mode at ${url}. Nothing to do.`);
330
- }
331
- return errorResult(`reconnect_gui relaunches the GUI through the proxy only. The GUI is in standalone mode (APP_PORT=${appPort}) and is not running (status: ${guiLauncher.getStatus()}). Free port ${appPort} or set another APP_PORT, then restart the MCP server. To use the proxy instead, set PROXY_URL and call reconnect_gui again.`);
332
- }
333
- // --- Synchronisation des alertes ---------------------------------------------------
334
- const SYNC_CHECK_MS = 60_000;
335
- let syncing = false;
336
- /**
337
- * Relit les alertes des dépôts dont la dernière lecture date de plus de 10
338
- * minutes, et le statut de la tâche organizer du dernier rapport de Claude.
339
- */
340
- async function syncStaleRepos() {
341
- if (syncing || !githubConfigured())
342
- return;
343
- syncing = true;
344
- try {
345
- const config = readGitHubConfig();
346
- for (const repo of staleRepos(store, SYNC_INTERVAL_MS)) {
347
- const synced = await syncRepository(store, config, repo.id);
348
- if (synced.syncError)
349
- logger.warn(`Dependabot alerts of ${repo.id} not synced: ${synced.syncError}`);
350
- await refreshReportTask(store, readSettings(dataDir), repo.id).catch((err) => logger.warn(`Organizer task of ${repo.id} not refreshed: ${err?.message ?? err}`));
351
- }
352
- }
353
- catch (err) {
354
- logger.error(`Alert sync failed: ${err?.stack ?? err}`);
355
- }
356
- finally {
357
- syncing = false;
358
- }
359
- }
360
- // --- Outils -------------------------------------------------------------------
361
- const REPOSITORY_DOC = "Tracked repository, as owner/name (see list_repositories).";
362
- const SCOPE_PROPERTY = {
363
- type: "string",
364
- enum: [...AUDIT_SCOPES],
365
- description: "production (default): npm audit and its fixes run with --omit=dev and leave the devDependencies out. all: every dependency, devDependencies included.",
366
- };
367
- const TOOLS = [
368
- {
369
- name: "list_repositories",
370
- description: "List the tracked repositories that are not deprecated, with their category, their analysed branch, their open Dependabot alerts by severity, the time of the last sync, the rights the user gave you (audit, fix, push), the pull requests the tracker opened that are still open, and the operation in progress. Start here.",
371
- inputSchema: {
372
- type: "object",
373
- properties: { category: { type: "string", description: "Only list the repositories of this category, by name (case-insensitive). The user creates the categories in the GUI." } },
374
- },
375
- },
376
- {
377
- name: "get_alerts",
378
- description: "Read the open Dependabot alerts of a tracked repository from GitHub now, and list them from the most to the least severe: number, severity, package, ecosystem, manifest, whether the dependency is a runtime or a development one, summary, patched version and link.",
379
- inputSchema: {
380
- type: "object",
381
- properties: { repository: { type: "string", description: REPOSITORY_DOC } },
382
- required: ["repository"],
383
- },
384
- },
385
- {
386
- name: "run_audit",
387
- description: "Run npm audit on a temporary clone of the analysed branch, in every directory that holds a package-lock.json, and report the vulnerabilities with the fix npm proposes (none, within the declared ranges, or a major upgrade). Needs the audit right. Nothing is changed; the clone is deleted.",
388
- inputSchema: {
389
- type: "object",
390
- properties: { repository: { type: "string", description: REPOSITORY_DOC }, scope: SCOPE_PROPERTY },
391
- required: ["repository"],
392
- },
393
- },
394
- {
395
- name: "fix_vulnerabilities",
396
- description: "Fix the npm vulnerabilities of a tracked repository in a temporary clone of its analysed branch: npm audit, then npm audit fix --package-lock-only --ignore-scripts, then optionally a commit on a new branch fix/npm-audit-<date>-<time>, its push and a pull request to the analysed branch. " +
397
- "Needs the fix right, plus the push right with push. Without push, nothing leaves the clone: the result reports what the fixes change. Waits until the operation ends and reports the vulnerabilities before and after, the updated packages and the pull request.",
398
- inputSchema: {
399
- type: "object",
400
- properties: {
401
- repository: { type: "string", description: REPOSITORY_DOC },
402
- scope: SCOPE_PROPERTY,
403
- push: { type: "boolean", description: "Commit the fixes on a new branch, push it and open a pull request (default false)." },
404
- commit_message: { type: "string", description: "Commit message, also the pull request title (first line). Default \"fix(deps): resolve npm audit vulnerabilities\"." },
405
- },
406
- required: ["repository"],
407
- },
408
- },
409
- reconnectGuiToolDefinition(),
410
- ];
411
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
412
- /** Lien vers un écran de la GUI, ajouté aux résultats des opérations ; vide quand la GUI est désactivée. */
413
- function guiHint(hash) {
414
- const url = guiLauncher.getUrl();
415
- if (!url)
416
- return "";
417
- return `\n\nOpen in the GUI: ${url}#/${hash}`;
418
- }
419
- /** Ajoute au résultat d'une opération le lien vers son écran dans la GUI. */
420
- function withOperationLink({ result, operation }) {
421
- const hint = guiHint(`r/${operation.repoId}/op/${operation.id}`);
422
- return { ...result, content: [{ type: "text", text: result.content[0].text + hint }] };
423
- }
424
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
425
- const { name, arguments: args } = request.params;
426
- const params = (args ?? {});
427
- try {
428
- switch (name) {
429
- case "list_repositories":
430
- return listRepositories(store, params);
431
- case "get_alerts":
432
- return await getAlerts(store, readGitHubConfig(), params);
433
- case "run_audit":
434
- return withOperationLink(await runAudit(operations, params));
435
- case "fix_vulnerabilities":
436
- return withOperationLink(await fixVulnerabilities(operations, params));
437
- case "reconnect_gui":
438
- return await reconnectGui(params);
439
- default:
440
- throw new Error(`Tool not found: ${name}`);
441
- }
442
- }
443
- catch (error) {
444
- return errorResult(error.message);
445
- }
446
- });
447
- async function main() {
448
- const transport = new StdioServerTransport();
449
- await server.connect(transport);
450
- logger.info(`MCP Server connected and running on stdio (data dir: ${dataDir}, clone dir: ${cloneDir})`);
451
- for (const orphan of store.failOrphanedOperations())
452
- logger.warn(`Operation ${orphan.id} on ${orphan.repoId} was interrupted.`);
453
- launchGUI();
454
- void syncStaleRepos();
455
- setInterval(() => void syncStaleRepos(), SYNC_CHECK_MS).unref();
456
- }
457
- main().catch((err) => {
458
- logger.error(`Fatal error: ${err.message}`);
459
- process.exit(1);
460
- });
461
- process.on("uncaughtException", (err) => {
462
- logger.error(`Uncaught Exception in MASTER: ${err.message}`);
463
- logger.error(err.stack || "No stack trace");
464
- guiLauncher.getProcess()?.kill("SIGTERM");
465
- process.exit(1);
466
- });
57
+ export {};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Mode MCP, lancé par un agent : expose sur stdio les outils qui pilotent le
3
+ * serveur Dependabot Tracker de SERVER_URL, avec le token d'agent AGENT_TOKEN.
4
+ * Il ne fait aucun travail lui-même.
5
+ */
6
+ export declare function runMcp(): Promise<void>;
@@ -0,0 +1,59 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
4
+ import { parseServerUrl } from "./cli/setup-mcp.js";
5
+ import { AgentClient } from "./tools/client.js";
6
+ import { TOOLS, callTool } from "./tools/tools.js";
7
+ import { errorResult } from "./tools/types.js";
8
+ import { APP_VERSION } from "./version.js";
9
+ /** Présentation transmise au client MCP : concepts, déroulé et règles. */
10
+ const INSTRUCTIONS = `mcp-dependabot-tracker follows the Dependabot alerts of GitHub repositories and fixes their npm vulnerabilities. These tools drive a Dependabot Tracker server, the same one the user drives from its web GUI: you start audits and fixes as the user would, and the server runs them. You never run git or npm yourself.
11
+
12
+ Concepts:
13
+ - A **tracked repository** is a GitHub repository the user added in the GUI. Its open Dependabot alerts, and the pull requests the tracker opened that are not merged or closed yet, are read from GitHub and refreshed every 10 minutes.
14
+ - A **deprecated repository** is one the user set aside in the GUI: list_repositories leaves it out, and every tool refuses it until the user restores it.
15
+ - The **scope** of an audit or a fix is chosen at each launch: production (the default) runs npm audit and npm audit fix with --omit=dev, so the devDependencies are left out; all covers every dependency.
16
+ - The **analysed branch** of a repository is chosen by the user in the GUI (the default branch unless changed). Dependabot alerts always describe the default branch; npm audit describes the analysed branch.
17
+ - An **operation** is an audit or a fix, run by the server in a temporary clone of the analysed branch, deleted at the end. A fix runs npm audit fix with --package-lock-only and --ignore-scripts, then, when vulnerabilities remain, the fixes by Claude (unless you pass claude: false), then commits on a new branch fix/npm-audit-<date>-<time> and opens a pull request to the analysed branch.
18
+
19
+ Workflow:
20
+ 1. list_repositories to see the tracked repositories and their open alerts.
21
+ 2. get_alerts for the detail of the alerts of one repository.
22
+ 3. run_audit to see what npm audit reports, or fix_vulnerabilities to fix, on the production dependencies unless the user asks for all of them. Both return at once with the id of the operation.
23
+ 4. get_operation to follow the operation until it is done, failed or cancelled; cancel_operation to stop it.
24
+
25
+ Rules:
26
+ - One operation at a time per repository.`;
27
+ /** Lit une variable obligatoire du mode MCP ; arrête le processus si elle manque. */
28
+ function required(name, purpose) {
29
+ const value = process.env[name]?.trim();
30
+ if (!value) {
31
+ process.stderr.write(`${name} is not set: declare ${purpose} in the env block of mcp-dependabot-tracker.\n`);
32
+ process.exit(1);
33
+ }
34
+ return value;
35
+ }
36
+ /**
37
+ * Mode MCP, lancé par un agent : expose sur stdio les outils qui pilotent le
38
+ * serveur Dependabot Tracker de SERVER_URL, avec le token d'agent AGENT_TOKEN.
39
+ * Il ne fait aucun travail lui-même.
40
+ */
41
+ export async function runMcp() {
42
+ const url = parseServerUrl(required("SERVER_URL", "the address of the Dependabot Tracker server"), "SERVER_URL");
43
+ if ("error" in url) {
44
+ process.stderr.write(`${url.error}\n`);
45
+ process.exit(1);
46
+ }
47
+ const client = new AgentClient(url.url, required("AGENT_TOKEN", "an agent token, created in the settings of the server GUI"));
48
+ const server = new Server({ name: "mcp-dependabot-tracker", version: APP_VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
49
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
50
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
51
+ try {
52
+ return await callTool(client, request.params.name, request.params.arguments);
53
+ }
54
+ catch (err) {
55
+ return errorResult(err?.message ?? String(err));
56
+ }
57
+ });
58
+ await server.connect(new StdioServerTransport());
59
+ }