@agentrica/mcp 0.4.0 → 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.
@@ -1,7 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  // Server MCP di Agentrica su stdio: un prompt per agente e due tool (elenca_agenti, agente).
3
3
  // Con --agents (es. --agents aisa,aiwda-08) prompt e tool vedono solo la squadra; senza, tutti gli agenti.
4
- // Legge solo i file di agents/ all'avvio; non scrive file, non apre connessioni e non registra dati (scrive solo init).
4
+ // Legge solo i file di agents/ all'avvio; non scrive file e non registra dati (scrive solo init). Due connessioni:
5
+ // l'invio di una valutazione (F20, ratings.ts), solo dopo la conferma dell'utente, e da F23 il controllo della versione
6
+ // sul registro npm all'avvio (update.ts). --no-ratings toglie tool, modulo e promemoria; --no-update-check il controllo.
7
+ // Da F23 la valutazione la chiede il server con il modulo dell'elicitation MCP, se il client lo supporta: quando si
8
+ // carica un altro agente (per il precedente) e dopo 30 minuti d'uso, una volta per agente.
5
9
  // Con --panel (F14) apre anche il pannello locale su 127.0.0.1 (panel.ts), che legge plan/, audit/ e lo stato di git
6
10
  // della cartella corrente e aggiunge i tool open_panel e ask_user; le chiamate agli agenti restano solo in memoria.
7
11
  import { realpathSync } from "node:fs";
@@ -11,7 +15,9 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
15
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
16
  import { z } from "zod";
13
17
  import { openBrowser, startPanel } from "./panel.js";
14
- import { agentSummary, agentText, codeName, findAgent, selectSquad, VERSION } from "./prompt.js";
18
+ import { agentSummary, agentText, codeName, findAgent, introLine, promptName, selectSquad, VERSION } from "./prompt.js";
19
+ import { createRatings, formMessage, MAX_COMMENT, parseForm, previewText, RATING_FORM, RATINGS_URL, REMINDER_AFTER_MS } from "./ratings.js";
20
+ import { fetchLatest, installKind, isNewer, REGISTRY_URL, updateMessage } from "./update.js";
15
21
  // Un errore all'avvio ferma il server con una riga sola su stderr, che il client mostra nei log. Il messaggio può
16
22
  // contenere argomenti della configurazione del client: i caratteri di controllo (a capo, escape) diventano \uXXXX.
17
23
  function fail(message) {
@@ -22,15 +28,26 @@ function fail(message) {
22
28
  const reason = (error) => (error instanceof Error ? error.message : String(error));
23
29
  let spec;
24
30
  let withPanel = false;
31
+ let withRatings = true;
32
+ let withUpdateCheck = true;
25
33
  // `init` (F18) crea un progetto e termina, senza avviare il server: è l'unico comando che scrive file (init.ts).
34
+ // `add` e `install` (F23) registrano il server in Claude Code e terminano (setup.ts).
26
35
  if (process.argv[2] === "init") {
27
36
  const { runInit } = await import("./init.js");
28
37
  process.exit(runInit(process.argv.slice(3)));
29
38
  }
39
+ if (process.argv[2] === "add" || process.argv[2] === "install") {
40
+ const { runSetup } = await import("./setup.js");
41
+ process.exit(runSetup(process.argv[2], process.argv.slice(3)));
42
+ }
30
43
  try {
31
- const { values } = parseArgs({ options: { agents: { type: "string" }, panel: { type: "boolean" } } });
44
+ const { values } = parseArgs({
45
+ options: { agents: { type: "string" }, panel: { type: "boolean" }, "no-ratings": { type: "boolean" }, "no-update-check": { type: "boolean" } },
46
+ });
32
47
  spec = values.agents;
33
48
  withPanel = values.panel ?? false;
49
+ withRatings = !values["no-ratings"];
50
+ withUpdateCheck = !values["no-update-check"];
34
51
  }
35
52
  catch (error) {
36
53
  fail(reason(error));
@@ -53,45 +70,148 @@ catch (error) {
53
70
  const all = catalog.flatMap((department) => department.agents.map((agent) => ({ department, agent })));
54
71
  const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
55
72
  const codes = catalog.map((d) => d.code);
73
+ // AGENTRICA_RATINGS_URL e AGENTRICA_REGISTRY_URL servono solo ai test (endpoint finti) e valgono solo su 127.0.0.1:
74
+ // un .mcp.json di un progetto non può dirottare le connessioni verso un altro server. In uso restano gli URL fissi.
75
+ const local = (name, fixed) => {
76
+ const url = process.env[name];
77
+ return url && /^http:\/\/127\.0\.0\.1:\d+\//.test(url) ? url : fixed;
78
+ };
79
+ const ratings = withRatings ? createRatings({ version: VERSION, url: local("AGENTRICA_RATINGS_URL", RATINGS_URL) }) : undefined;
80
+ // Frasi per il modello in coda alla risposta del prossimo tool di Agentrica: l'avviso di versione nuova (una volta) e
81
+ // l'esito di un modulo di valutazione mostrato fuori da una chiamata.
82
+ const notes = [];
83
+ let update;
84
+ if (withUpdateCheck) {
85
+ void fetchLatest(local("AGENTRICA_REGISTRY_URL", REGISTRY_URL)).then((version) => {
86
+ if (!version || !isNewer(version, VERSION))
87
+ return;
88
+ update = updateMessage(VERSION, version, installKind(import.meta.filename));
89
+ notes.push(`Avviso per l'utente, da riferire una volta: ${update}`);
90
+ });
91
+ }
56
92
  let panel;
57
93
  if (withPanel) {
58
94
  try {
59
- panel = await startPanel(realpathSync(process.cwd()));
95
+ const panelRatings = ratings && {
96
+ isRated: ratings.isRated,
97
+ rate: (input) => ratings.send(ratings.build(input)),
98
+ };
99
+ panel = await startPanel(realpathSync(process.cwd()), panelRatings, () => update);
60
100
  }
61
101
  catch (error) {
62
102
  fail(`pannello non avviato: ${reason(error)}`);
63
103
  }
64
104
  }
65
- /** Registra nel pannello che un agente è stato usato: id, nome in codice, ruolo e l'inizio del compito. */
66
- function used({ department, agent }, task) {
105
+ let current;
106
+ /**
107
+ * Un agente è stato caricato: lo registra nel pannello (id, nome in codice, ruolo, reparto e l'inizio del compito) e,
108
+ * se prima ne era in uso un altro, chiede la valutazione di quello, che ha finito. Restituisce l'esito del modulo.
109
+ */
110
+ async function used({ department, agent }, task) {
111
+ const previous = current;
112
+ current = agent.id;
113
+ if (ratings && !ratings.isRated(agent.id) && canAsk()) {
114
+ // Il timer dei 30 minuti (unref: non tiene vivo il processo). Solo al primo caricamento dell'agente.
115
+ if (!timers.has(agent.id))
116
+ timers.set(agent.id, setTimeout(() => void askLater(agent.id), REMINDER_AFTER_MS).unref());
117
+ }
118
+ ratings?.loaded(agent.id);
67
119
  const line = (task ?? "").replace(/\s+/g, " ").trim();
68
120
  panel?.record({
69
121
  id: agent.id,
70
122
  codeName: codeName(agent),
71
123
  role: agent.role,
72
- department: department.code,
124
+ department: `${department.code} · ${department.short}`,
73
125
  task: line.length > 120 ? `${line.slice(0, 119)}…` : line,
74
126
  });
127
+ if (!previous || previous === agent.id)
128
+ return undefined;
129
+ try {
130
+ return await askRating(previous);
131
+ }
132
+ catch {
133
+ // Il client non ha mostrato il modulo (errore o tempo scaduto): l'agente si carica lo stesso, resta il promemoria.
134
+ ratings?.unclaimAsk(previous);
135
+ return undefined;
136
+ }
137
+ }
138
+ const timers = new Map();
139
+ const FORM_TIMEOUT_MS = 5 * 60_000;
140
+ /** Il client mostra moduli (elicitation MCP)? Senza, resta il flusso di F20: rate_agent proposto dal modello. */
141
+ function canAsk() {
142
+ return Boolean(server.server.getClientCapabilities()?.elicitation?.form);
143
+ }
144
+ /** Mostra il modulo di valutazione per un agente, una volta; restituisce la frase per il modello con l'esito. */
145
+ async function askRating(agentId) {
146
+ const found = findAgent(catalog, agentId);
147
+ if (!ratings || !found || !canAsk() || !ratings.claimAsk(agentId))
148
+ return undefined;
149
+ const name = codeName(found.agent);
150
+ const result = await server.server.elicitInput({ message: formMessage(introLine(found)), requestedSchema: RATING_FORM }, { timeout: FORM_TIMEOUT_MS });
151
+ if (result.action !== "accept")
152
+ return undefined;
153
+ const input = parseForm(agentId, result.content);
154
+ if (!input)
155
+ return `La valutazione di ${name} non è partita: il modulo aveva dati non validi.`;
156
+ const sent = await ratings.send(ratings.build(input));
157
+ return sent.ok
158
+ ? `L'utente ha valutato ${name} con il modulo: inviata, codice ${sent.usageId}. Diglielo: con questo codice può chiedere di cancellarla o di non pubblicare il commento (note legali di Agentrica).`
159
+ : `La valutazione di ${name} non è partita: ${sent.message}`;
160
+ }
161
+ /** Il modulo dei 30 minuti, fuori da una chiamata. Se il client non lo accetta, resta il promemoria in coda (remind). */
162
+ async function askLater(agentId) {
163
+ try {
164
+ const note = await askRating(agentId);
165
+ if (note)
166
+ notes.push(note);
167
+ }
168
+ catch {
169
+ ratings?.unclaimAsk(agentId);
170
+ }
75
171
  }
76
172
  const server = new McpServer({ name: "agentrica", version: VERSION }, {
77
173
  instructions: `Agentrica: ${count(all.length, "agente IA", "agenti IA")} in ${count(catalog.length, "reparto", "reparti")} (${codes.join(", ")}). ` +
78
174
  "Per scegliere un agente usa elenca_agenti; per lavorare come quell'agente carica le sue istruzioni con agente. " +
79
- `I prompt hanno il nome dell'id dell'agente, es. ${all[0].agent.id.toLowerCase()}.` +
175
+ `I prompt hanno il nome dell'id dell'agente e del reparto, es. ${promptName(all[0])}; il tool agente vuole l'id, es. ${all[0].agent.id}.` +
80
176
  (panel
81
177
  ? " Il pannello locale è attivo: per le scelte che spettano all'utente usa ask_user, che mostra la domanda nella pagina; open_panel dà l'URL della pagina."
178
+ : "") +
179
+ (ratings
180
+ ? " Se il testo di un agente chiede di proporre la valutazione, fallo con rate_agent (una volta per agente per sessione); niente parte senza il sì dell'utente all'anteprima."
82
181
  : ""),
83
182
  });
84
183
  const TASK = z.string().max(20_000).optional().describe("Il compito da affidare all'agente nel progetto corrente.");
85
184
  const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
86
185
  // Id ammesso: una sigla di tutto il catalogo (non solo della squadra, così fuori squadra è «non trovato») e due cifre.
87
186
  const ID = new RegExp(`^(?:${full.map((d) => d.code).join("|")})-\\d{2}$`, "i");
187
+ const AGENT_ID = z.string().regex(ID, "Formato dell'id: SIGLA-NN, es. AISA-02.").describe("Id dell'agente, es. AISA-02.");
188
+ /**
189
+ * In coda alla risposta di un tool: le frasi in attesa (versione nuova, esito di un modulo) e il promemoria di F20
190
+ * (agenti in uso da 30 minuti e non valutati, una volta per agente) per i client senza moduli.
191
+ */
192
+ function remind(result, ...extra) {
193
+ const lines = [...extra.filter((line) => line !== undefined), ...notes.splice(0)];
194
+ const due = ratings?.due() ?? [];
195
+ if (due.length > 0) {
196
+ const names = due.map((id) => findAgent(catalog, id)).filter((f) => f !== undefined).map((f) => codeName(f.agent));
197
+ lines.push(`Promemoria per il modello: ${names.join(", ")} ${names.length === 1 ? "è" : "sono"} in uso da più di 30 minuti. A un punto naturale del lavoro proponi all'utente di valutarl${names.length === 1 ? "o" : "i"} con rate_agent; se rifiuta, non chiedere più.`);
198
+ }
199
+ if (lines.length === 0)
200
+ return result;
201
+ return { ...result, content: [...result.content, ...lines.map((text) => ({ type: "text", text }))] };
202
+ }
203
+ /** La proposta di valutazione nel testo dell'agente serve solo ai client senza moduli. */
204
+ const textOptions = () => ({ ratings: Boolean(ratings) && !canAsk() });
88
205
  for (const found of all) {
89
206
  const title = `${codeName(found.agent)} — ${found.agent.role}`;
90
- server.registerPrompt(found.agent.id.toLowerCase(), { title, description: agentSummary(found), argsSchema: { compito: TASK } }, ({ compito }) => {
91
- used(found, compito);
207
+ server.registerPrompt(promptName(found), { title, description: agentSummary(found), argsSchema: { compito: TASK } }, async ({ compito }) => {
208
+ // Un prompt non ha una risposta di tool: l'esito del modulo va alla prossima.
209
+ const note = await used(found, compito);
210
+ if (note)
211
+ notes.push(note);
92
212
  return {
93
213
  description: title,
94
- messages: [{ role: "user", content: { type: "text", text: agentText(found, compito) } }],
214
+ messages: [{ role: "user", content: { type: "text", text: agentText(found, compito, textOptions()) } }],
95
215
  };
96
216
  });
97
217
  }
@@ -109,17 +229,17 @@ server.registerTool("elenca_agenti", {
109
229
  ...d.agents.map((agent) => `- ${codeName(agent)}: ${agentSummary({ department: d, agent })}`),
110
230
  "",
111
231
  ]);
112
- return { content: [{ type: "text", text: lines.join("\n") }] };
232
+ return remind({ content: [{ type: "text", text: lines.join("\n") }] });
113
233
  });
114
234
  server.registerTool("agente", {
115
235
  title: "Istruzioni di un agente",
116
236
  description: "Restituisce le istruzioni complete di un agente (regole comuni del reparto e file di ruolo), da seguire per lavorare come quell'agente.",
117
237
  inputSchema: {
118
- id: z.string().regex(ID, "Formato dell'id: SIGLA-NN, es. AISA-02.").describe("Id dell'agente, es. AISA-02."),
238
+ id: AGENT_ID,
119
239
  compito: TASK,
120
240
  },
121
241
  annotations: READ_ONLY,
122
- }, ({ id, compito }) => {
242
+ }, async ({ id, compito }) => {
123
243
  const found = findAgent(catalog, id);
124
244
  if (!found) {
125
245
  return {
@@ -127,9 +247,53 @@ server.registerTool("agente", {
127
247
  content: [{ type: "text", text: "Agente non trovato: usa elenca_agenti per vedere gli id." }],
128
248
  };
129
249
  }
130
- used(found, compito);
131
- return { content: [{ type: "text", text: agentText(found, compito) }] };
250
+ const note = await used(found, compito);
251
+ return remind({ content: [{ type: "text", text: agentText(found, compito, textOptions()) }] }, note);
132
252
  });
253
+ if (ratings)
254
+ registerRatingTool(ratings);
255
+ function registerRatingTool(ratings) {
256
+ server.registerTool("rate_agent", {
257
+ title: "Valuta un agente di Agentrica",
258
+ description: "Invia ad Agentrica la valutazione di un agente (voto 1–5, commento facoltativo), in forma anonima, in due passi. " +
259
+ "1) Senza code: restituisce l'anteprima di ciò che parte e un codice. 2) Mostra l'anteprima all'utente, chiedigli se inviarla " +
260
+ "e solo dopo il suo sì richiama il tool con quel code. Non inviare mai senza il sì dell'utente; non mettere nel commento codice, " +
261
+ "file o dati del progetto, solo le parole dell'utente.",
262
+ inputSchema: {
263
+ id: AGENT_ID,
264
+ rating: z.number().int().min(1).max(5).optional().describe("Voto da 1 a 5 (primo passo)."),
265
+ comment: z.string().max(MAX_COMMENT).optional().describe("Cosa è andato bene o cosa migliorare, con le parole dell'utente (primo passo)."),
266
+ publish: z.boolean().optional().describe("true se l'utente permette di pubblicare il commento sul sito; predefinito false (primo passo)."),
267
+ code: z.string().regex(/^[0-9a-f]{8}$/).optional().describe("Il codice dell'anteprima, solo dopo il sì dell'utente (secondo passo)."),
268
+ },
269
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
270
+ }, async ({ id, rating, comment, publish, code }) => {
271
+ const found = findAgent(catalog, id);
272
+ const fail = (text) => ({ isError: true, content: [{ type: "text", text }] });
273
+ if (!found)
274
+ return fail("Agente non trovato: usa elenca_agenti per vedere gli id.");
275
+ if (ratings.isRated(found.agent.id))
276
+ return fail(`${codeName(found.agent)} è già stato valutato in questa sessione.`);
277
+ if (code) {
278
+ const result = await ratings.confirm(code, found.agent.id);
279
+ if (!result.ok)
280
+ return fail(result.message);
281
+ return {
282
+ content: [
283
+ {
284
+ type: "text",
285
+ text: `Valutazione di ${codeName(found.agent)} inviata, grazie. Codice della valutazione: ${result.usageId}. ` +
286
+ "Dillo all'utente: con questo codice può chiedere di cancellarla o di non pubblicare il commento (note legali di Agentrica).",
287
+ },
288
+ ],
289
+ };
290
+ }
291
+ if (rating === undefined)
292
+ return fail("Serve il voto da 1 a 5 per preparare l'anteprima.");
293
+ const draft = ratings.draft({ agentId: found.agent.id, rating, comment, publish });
294
+ return { content: [{ type: "text", text: previewText(introLine(found), draft.code, draft.rating) }] };
295
+ });
296
+ }
133
297
  if (panel)
134
298
  registerPanelTools(panel);
135
299
  function registerPanelTools(panel) {
@@ -143,9 +307,9 @@ function registerPanelTools(panel) {
143
307
  annotations: { readOnlyHint: true, openWorldHint: false },
144
308
  }, () => {
145
309
  openBrowser(panel.url);
146
- return {
310
+ return remind({
147
311
  content: [{ type: "text", text: `Pannello aperto nel browser. Se non si è aperto, l'utente può aprire questo URL, valido solo su questo computer: ${panel.url}` }],
148
- };
312
+ });
149
313
  });
150
314
  const option = z.object({
151
315
  label: z.string().min(1).max(80).describe("Etichetta breve dell'opzione."),
@@ -185,7 +349,7 @@ function registerPanelTools(panel) {
185
349
  try {
186
350
  const answer = await panel.ask({ question, header: header ?? "", options, multiple: multiple ?? false }, AbortSignal.any([extra.signal, AbortSignal.timeout(wait)]));
187
351
  const chosen = answer.choices.length ? `L'utente ha scelto: ${answer.choices.join("; ")}.` : "L'utente non ha scelto un'opzione.";
188
- return { content: [{ type: "text", text: answer.note ? `${chosen}\nNota dell'utente: ${answer.note}` : chosen }] };
352
+ return remind({ content: [{ type: "text", text: answer.note ? `${chosen}\nNota dell'utente: ${answer.note}` : chosen }] });
189
353
  }
190
354
  catch {
191
355
  return {
@@ -0,0 +1,25 @@
1
+ export type Scope = "user" | "project" | "local";
2
+ export interface RunResult {
3
+ status: number | null;
4
+ stdout: string;
5
+ stderr: string;
6
+ /** Il programma non c'è (ENOENT). */
7
+ missing?: boolean;
8
+ }
9
+ export interface SetupDeps {
10
+ platform: NodeJS.Platform;
11
+ nodeVersion: string;
12
+ run(command: string, args: string[]): RunResult;
13
+ exists(path: string): boolean;
14
+ out(text: string): void;
15
+ }
16
+ /**
17
+ * Su Windows npm e (se installato con npm) claude sono file .cmd, che Node non avvia senza shell: si passa da
18
+ * cmd.exe con ogni argomento fra virgolette. Gli argomenti sono nostri; con " o % (che cmd espande anche fra
19
+ * virgolette) il comando non parte e si stampa quello da lanciare a mano.
20
+ */
21
+ export declare function cmdLine(command: string, args: string[]): string | undefined;
22
+ /** Il comando con cui il client avvia il server. */
23
+ export declare function serverCommand(mode: "add" | "install", platform: NodeJS.Platform, flags: string[], globalRoot?: string): string[];
24
+ /** Esegue il comando; restituisce il codice di uscita. */
25
+ export declare function runSetup(mode: "add" | "install", args: string[], deps?: SetupDeps): number;
@@ -0,0 +1,161 @@
1
+ // `agentrica-mcp add` e `agentrica-mcp install` (F23): registrano il server in Claude Code con un solo comando, uguale su
2
+ // Mac, Windows e Linux. Chiamano `claude mcp add` (e per install `npm install -g`) senza shell, con gli argomenti in un
3
+ // array: niente quoting di PowerShell, cmd, zsh o bash. La versione è sempre quella di questo pacchetto, fissata.
4
+ // - add: il server parte con npx (su Windows `cmd /c npx`, perché npx è npx.cmd); ambito user, --project o --local.
5
+ // - install: installa questa versione con npm -g e registra `node <cartella globale>/…/server.js` con ambito user.
6
+ // Una registrazione con lo stesso nome nello stesso ambito si sostituisce: rilanciare con una versione nuova aggiorna.
7
+ // Se mancano Node ≥ 22, npm o claude, lo dice e stampa i comandi da lanciare a mano.
8
+ import { spawnSync } from "node:child_process";
9
+ import { existsSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { parseArgs } from "node:util";
12
+ import { VERSION } from "./prompt.js";
13
+ const NAME = "agentrica";
14
+ const PACKAGE = `@agentrica/mcp@${VERSION}`;
15
+ const SERVER_IN_PACKAGE = ["@agentrica", "mcp", "dist", "mcp", "src", "server.js"];
16
+ /**
17
+ * Su Windows npm e (se installato con npm) claude sono file .cmd, che Node non avvia senza shell: si passa da
18
+ * cmd.exe con ogni argomento fra virgolette. Gli argomenti sono nostri; con " o % (che cmd espande anche fra
19
+ * virgolette) il comando non parte e si stampa quello da lanciare a mano.
20
+ */
21
+ export function cmdLine(command, args) {
22
+ const all = [command, ...args];
23
+ if (all.some((arg) => /["%\r\n]/.test(arg)))
24
+ return undefined;
25
+ return `"${all.map((arg) => `"${arg}"`).join(" ")}"`;
26
+ }
27
+ function realRun(platform) {
28
+ return (command, args) => {
29
+ const direct = spawnSync(command, args, { encoding: "utf8" });
30
+ const missing = direct.error?.code === "ENOENT";
31
+ if (!(missing && platform === "win32"))
32
+ return { status: direct.status, stdout: direct.stdout ?? "", stderr: direct.stderr ?? "", missing };
33
+ const line = cmdLine(command, args);
34
+ if (!line)
35
+ return { status: null, stdout: "", stderr: "", missing: true };
36
+ const viaCmd = spawnSync("cmd.exe", ["/d", "/s", "/c", line], { encoding: "utf8", windowsVerbatimArguments: true });
37
+ // cmd risponde 9009 quando il comando non esiste.
38
+ return { status: viaCmd.status, stdout: viaCmd.stdout ?? "", stderr: viaCmd.stderr ?? "", missing: viaCmd.status === 9009 };
39
+ };
40
+ }
41
+ const REAL = {
42
+ platform: process.platform,
43
+ nodeVersion: process.versions.node,
44
+ run: realRun(process.platform),
45
+ exists: existsSync,
46
+ out: (text) => process.stdout.write(text),
47
+ };
48
+ /** Il comando con cui il client avvia il server. */
49
+ export function serverCommand(mode, platform, flags, globalRoot = "") {
50
+ if (mode === "install")
51
+ return ["node", join(globalRoot, ...SERVER_IN_PACKAGE), ...flags];
52
+ const npx = ["npx", "-y", PACKAGE, ...flags];
53
+ return platform === "win32" ? ["cmd", "/c", ...npx] : npx;
54
+ }
55
+ /** Il comando da scrivere nel terminale, per i messaggi: gli argomenti con spazi fra virgolette. */
56
+ const shown = (args) => args.map((arg) => (/[\s"]/.test(arg) ? `"${arg}"` : arg)).join(" ");
57
+ const SCOPE_TEXT = {
58
+ user: "ambito user: tutti i tuoi progetti",
59
+ project: "ambito project: .mcp.json in questa cartella, per il team",
60
+ local: "ambito local: solo questo progetto, solo per te",
61
+ };
62
+ /** Esegue il comando; restituisce il codice di uscita. */
63
+ export function runSetup(mode, args, deps = REAL) {
64
+ const say = (line = "") => deps.out(`${line}\n`);
65
+ let scope = "user";
66
+ const flags = [];
67
+ let from;
68
+ try {
69
+ const { values } = parseArgs({
70
+ args,
71
+ options: {
72
+ project: { type: "boolean" },
73
+ local: { type: "boolean" },
74
+ agents: { type: "string" },
75
+ panel: { type: "boolean" },
76
+ "no-ratings": { type: "boolean" },
77
+ "no-update-check": { type: "boolean" },
78
+ // ponytail: --from installa da un .tgz di npm pack, per provare install prima del rilascio (F23-10).
79
+ from: { type: "string" },
80
+ },
81
+ });
82
+ if (values.project && values.local)
83
+ throw new Error("scegli --project o --local, non entrambi");
84
+ if (mode === "install" && (values.project || values.local))
85
+ throw new Error("install registra sempre con ambito user; per un progetto usa add --project o add --local");
86
+ if (mode === "add" && values.from)
87
+ throw new Error("--from vale solo per install");
88
+ scope = values.project ? "project" : values.local ? "local" : "user";
89
+ if (values.agents !== undefined) {
90
+ if (!/^[A-Za-z0-9,-]{1,300}$/.test(values.agents))
91
+ throw new Error("--agents: id di agenti e sigle di reparti separati da virgole, es. --agents aisa,aiwda-08");
92
+ flags.push("--agents", values.agents);
93
+ }
94
+ if (values.panel)
95
+ flags.push("--panel");
96
+ if (values["no-ratings"])
97
+ flags.push("--no-ratings");
98
+ if (values["no-update-check"])
99
+ flags.push("--no-update-check");
100
+ from = values.from;
101
+ }
102
+ catch (error) {
103
+ say(`agentrica ${mode}: ${(error instanceof Error ? error.message : String(error)).replace(/\p{Cc}/gu, " ")}`);
104
+ return 1;
105
+ }
106
+ const win = deps.platform === "win32";
107
+ const manual = (steps) => {
108
+ say("Comandi da lanciare a mano:");
109
+ for (const step of steps)
110
+ say(` ${step}`);
111
+ };
112
+ if (Number(deps.nodeVersion.split(".")[0]) < 22) {
113
+ say(`agentrica ${mode}: serve Node.js 22 o più recente (in uso ${deps.nodeVersion}). Installalo da https://nodejs.org e rilancia:`);
114
+ say(` npx -y ${PACKAGE} ${mode}`);
115
+ return 1;
116
+ }
117
+ let command;
118
+ if (mode === "install") {
119
+ const install = deps.run("npm", ["install", "-g", from ?? PACKAGE]);
120
+ if (install.missing) {
121
+ say("agentrica install: npm non trovato. Installa Node.js 22 o più recente (con npm) da https://nodejs.org e rilancia.");
122
+ return 1;
123
+ }
124
+ if (install.status !== 0) {
125
+ say(`agentrica install: npm install -g non riuscito.${win ? "" : " Se è un problema di permessi, configura una cartella globale di npm tua (npm config set prefix) invece di usare sudo."}`);
126
+ if (install.stderr.trim())
127
+ say(install.stderr.trim());
128
+ return 1;
129
+ }
130
+ const root = deps.run("npm", ["root", "-g"]).stdout.trim();
131
+ command = serverCommand("install", deps.platform, flags, root);
132
+ if (!root || !deps.exists(command[1])) {
133
+ say(`agentrica install: pacchetto installato ma server non trovato in ${root || "(cartella globale di npm sconosciuta)"}.`);
134
+ return 1;
135
+ }
136
+ say(`Installato ${from ? from : PACKAGE} in ${root}.`);
137
+ }
138
+ else {
139
+ command = serverCommand("add", deps.platform, flags);
140
+ }
141
+ const addArgs = ["mcp", "add", "--scope", scope, NAME, "--", ...command];
142
+ const removed = deps.run("claude", ["mcp", "remove", NAME, "--scope", scope]);
143
+ if (removed.missing) {
144
+ say("agentrica: Claude Code (comando claude) non trovato. Installalo e rilancia questo comando, oppure registra il server a mano:");
145
+ manual([shown(["claude", ...addArgs])]);
146
+ say("Per altri client MCP usa lo stesso comando del server nella loro configurazione (README di @agentrica/mcp).");
147
+ return 1;
148
+ }
149
+ const added = deps.run("claude", addArgs);
150
+ if (added.status !== 0) {
151
+ say("agentrica: claude mcp add non riuscito.");
152
+ if ((added.stderr || added.stdout).trim())
153
+ say((added.stderr || added.stdout).trim());
154
+ manual([shown(["claude", ...addArgs])]);
155
+ return 1;
156
+ }
157
+ say(`Agentrica ${VERSION} registrato in Claude Code (${SCOPE_TEXT[scope]})${removed.status === 0 ? ", al posto della registrazione precedente" : ""}.`);
158
+ say(`Comando del server: ${shown(command)}`);
159
+ say("Riavvia Claude Code (o usa /mcp) e controlla con: claude mcp list");
160
+ return 0;
161
+ }
@@ -0,0 +1,10 @@
1
+ export declare const REGISTRY_URL = "https://registry.npmjs.org/-/package/@agentrica/mcp/dist-tags";
2
+ /** Come è installato il server: dalla cartella globale di npm (`install`), dalla cache di npx (`add`, `init`) o da un clone. */
3
+ export type InstallKind = "global" | "npx" | "source";
4
+ export declare function installKind(serverPath: string): InstallKind;
5
+ /** true se `latest` è una versione x.y.z più nuova di `current`. */
6
+ export declare function isNewer(latest: string, current: string): boolean;
7
+ /** La versione `latest` del registro, o undefined per qualunque problema. */
8
+ export declare function fetchLatest(url?: string, doFetch?: typeof fetch): Promise<string | undefined>;
9
+ /** L'avviso per l'utente (anche nel banner del pannello), con il comando giusto per come è installato il server. */
10
+ export declare function updateMessage(current: string, latest: string, kind: InstallKind): string;
@@ -0,0 +1,65 @@
1
+ // Controllo della versione nuova (F23): all'avvio una GET ai dist-tag di @agentrica/mcp sul registro npm, senza
2
+ // parametri né dati. La risposta è un dato esterno: se ne legge al più MAX_BYTES, si accetta solo una versione semver
3
+ // x.y.z e nel testo per il modello entra solo quella. Rete assente o negata, timeout, risposta strana: niente avviso.
4
+ // La versione resta fissata: l'avviso dice solo come aggiornare. --no-update-check lo spegne.
5
+ export const REGISTRY_URL = "https://registry.npmjs.org/-/package/@agentrica/mcp/dist-tags";
6
+ const TIMEOUT_MS = 3_000;
7
+ const MAX_BYTES = 4_096;
8
+ const SEMVER = /^(\d{1,6})\.(\d{1,6})\.(\d{1,6})$/;
9
+ export function installKind(serverPath) {
10
+ if (/[\\/]_npx[\\/]/.test(serverPath))
11
+ return "npx";
12
+ if (/[\\/]node_modules[\\/]@agentrica[\\/]mcp[\\/]/.test(serverPath))
13
+ return "global";
14
+ return "source";
15
+ }
16
+ /** true se `latest` è una versione x.y.z più nuova di `current`. */
17
+ export function isNewer(latest, current) {
18
+ const a = SEMVER.exec(latest);
19
+ const b = SEMVER.exec(current);
20
+ if (!a || !b)
21
+ return false;
22
+ for (let i = 1; i <= 3; i++) {
23
+ const diff = Number(a[i]) - Number(b[i]);
24
+ if (diff !== 0)
25
+ return diff > 0;
26
+ }
27
+ return false;
28
+ }
29
+ /** La versione `latest` del registro, o undefined per qualunque problema. */
30
+ export async function fetchLatest(url = REGISTRY_URL, doFetch = fetch) {
31
+ try {
32
+ const response = await doFetch(url, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) });
33
+ if (!response.ok || !response.body)
34
+ return undefined;
35
+ const reader = response.body.getReader();
36
+ const chunks = [];
37
+ let size = 0;
38
+ for (;;) {
39
+ const { done, value } = await reader.read();
40
+ if (done)
41
+ break;
42
+ size += value.byteLength;
43
+ if (size > MAX_BYTES) {
44
+ await reader.cancel();
45
+ return undefined;
46
+ }
47
+ chunks.push(value);
48
+ }
49
+ const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
50
+ const latest = typeof data === "object" && data !== null ? data.latest : undefined;
51
+ return typeof latest === "string" && SEMVER.test(latest) ? latest : undefined;
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ /** L'avviso per l'utente (anche nel banner del pannello), con il comando giusto per come è installato il server. */
58
+ export function updateMessage(current, latest, kind) {
59
+ const how = kind === "global"
60
+ ? `Per aggiornare: npx -y @agentrica/mcp@${latest} install, poi riavvia il client.`
61
+ : kind === "npx"
62
+ ? `Per aggiornare cambia la versione in @agentrica/mcp@${latest} nel comando del server (claude mcp add o .mcp.json), poi riavvia il client.`
63
+ : "Per aggiornare il clone: git pull, poi riavvia il client.";
64
+ return `È uscita la versione ${latest} di Agentrica (in uso la ${current}). ${how}`;
65
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@agentrica/mcp",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "mcpName": "io.github.flgisimone/agentrica",
5
- "description": "I 56 agenti IA di Agentrica come server MCP locale (stdio): un prompt per agente e due tool in sola lettura.",
5
+ "description": "I 56 agenti IA di Agentrica come server MCP locale (stdio): un prompt per agente, due tool in sola lettura e un tool per valutare gli agenti.",
6
6
  "license": "MIT",
7
7
  "author": "Giulio Simone Floresta",
8
8
  "repository": {
@@ -17,7 +17,8 @@
17
17
  "types": "./dist/mcp/src/catalog.d.ts",
18
18
  "default": "./dist/mcp/src/catalog.js"
19
19
  },
20
- "./package.json": "./package.json"
20
+ "./package.json": "./package.json",
21
+ "./CHANGELOG.md": "./CHANGELOG.md"
21
22
  },
22
23
  "bin": {
23
24
  "agentrica-mcp": "dist/mcp/src/server.js"
@@ -27,7 +28,8 @@
27
28
  "agents",
28
29
  "starter",
29
30
  ".claude/agents",
30
- "README.en.md"
31
+ "README.en.md",
32
+ "CHANGELOG.md"
31
33
  ],
32
34
  "engines": {
33
35
  "node": ">=22"
@@ -148,7 +148,7 @@ Se un passo fallisce ci si ferma, si riferisce l'errore e non si salta ai passi
148
148
 
149
149
  ### 13.8 Rilascio in `main`
150
150
  Non fa parte della chiusura di una fase: si fa solo quando l'utente lo chiede, con la CI di `develop` verde.
151
- 1. Pull request da `develop` a `main` (`gh pr create --base main --head develop --title "Rilascio: FN descrizione breve"`), unita con merge commit quando la CI è verde (`gh pr merge --merge`). Conviene un ruleset su `main` che vieti push diretti e force push.
151
+ 1. Pull request da `develop` a `main` (`gh pr create --base main --head develop --title "Rilascio: FN descrizione breve"`), unita con merge commit quando la CI è verde (`gh pr merge --merge`). Conviene un ruleset su `main` che vieti push diretti e force push. **Subito dopo, `develop` torna allo stesso commit di `main`**: `git fetch`, su `develop` `git merge --ff-only origin/main`, push di `develop`, e `origin/develop` e `origin/main` devono avere lo stesso hash. Una nota scritta dopo il rilascio va in `main` con un'altra PR, poi si riallinea di nuovo. `develop` e `main` sono sempre allineati.
152
152
  2. <!-- Da compilare: hosting, cosa pubblica `main`, passi per le migrazioni, controllo dopo il deploy. -->
153
153
 
154
154
  Deploy e migrazioni in produzione partono sempre con un ok esplicito, a parte da quello della fase.