@imenam/mcp-organizer 1.0.1 → 1.0.3

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.
@@ -2,6 +2,7 @@ import { openDatabase } from "./db.js";
2
2
  import { ForbiddenError, InvariantError, NotFoundError, OrganizerError } from "./errors.js";
3
3
  import { positionBetween } from "../../shared/logic/positions.js";
4
4
  import { newId } from "./ids.js";
5
+ import { WatcherRegistry } from "./watchers.js";
5
6
  import { MAX_TASK_DEPTH, } from "../../shared/schemas/enums.schema.js";
6
7
  import { AccessLinkSchema, AgentActionSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, EntityVersionSchema, IdeaSchema, IdeaSnapshotSchema, InvitationSchema, MembershipSchema, NotificationSchema, SessionSchema, SpaceSchema, TagSchema, TaskSchema, TaskSnapshotSchema, TestCheckpointSchema, TestResultSchema, TestReviewSchema, UserSchema, UserSettingsSchema, } from "../../shared/schemas/entities.schema.js";
7
8
  /** Valide `value` avec `schema` ; une donnée invalide est une erreur métier qui liste les champs fautifs. */
@@ -276,6 +277,9 @@ export class Store {
276
277
  db;
277
278
  activeMutation = null;
278
279
  emailListener = null;
280
+ pendingRequestListeners = new Set();
281
+ /** Présence des veilleurs de notifications, par jeton d'agent. */
282
+ watchers = new WatcherRegistry();
279
283
  constructor(db) {
280
284
  this.db = db;
281
285
  }
@@ -767,6 +771,15 @@ export class Store {
767
771
  setEmailListener(listener) {
768
772
  this.emailListener = listener;
769
773
  }
774
+ /**
775
+ * Abonne `listener` aux demandes qui passent en attente (créées, ou
776
+ * libérées par un membre) : il les reçoit après la validation de la
777
+ * mutation. La fonction rendue désabonne.
778
+ */
779
+ onPendingRequest(listener) {
780
+ this.pendingRequestListeners.add(listener);
781
+ return () => this.pendingRequestListeners.delete(listener);
782
+ }
770
783
  /**
771
784
  * Point unique d'écriture. `fn` reçoit une `Mutation` et s'exécute dans une
772
785
  * transaction exclusive ; à sa sortie, les invariants sont vérifiés sur l'état
@@ -777,6 +790,7 @@ export class Store {
777
790
  if (this.activeMutation)
778
791
  throw new Error("Store.mutate is not reentrant: use the Mutation passed to the running mutation.");
779
792
  let emails = [];
793
+ let pending = [];
780
794
  const run = this.db.transaction(() => {
781
795
  const tx = new Mutation(this, actor);
782
796
  this.activeMutation = tx;
@@ -784,6 +798,7 @@ export class Store {
784
798
  const result = fn(tx);
785
799
  tx.finish();
786
800
  emails = tx.emailNotificationIds;
801
+ pending = tx.pendingRequestIds;
787
802
  return result;
788
803
  }
789
804
  finally {
@@ -793,6 +808,13 @@ export class Store {
793
808
  const result = run.immediate();
794
809
  if (emails.length > 0 && this.emailListener)
795
810
  this.emailListener(emails);
811
+ if (pending.length > 0 && this.pendingRequestListeners.size > 0) {
812
+ for (const id of pending) {
813
+ const request = this.getAgentRequest(id);
814
+ for (const listener of [...this.pendingRequestListeners])
815
+ listener(request);
816
+ }
817
+ }
796
818
  return result;
797
819
  }
798
820
  }
@@ -809,6 +831,8 @@ export class Mutation {
809
831
  touched = new Map();
810
832
  /** Notifications créées par la mutation dont le destinataire veut un e-mail. */
811
833
  emailNotificationIds = [];
834
+ /** Demandes passées en attente par la mutation : créées, ou libérées. */
835
+ pendingRequestIds = [];
812
836
  /** Demande pour laquelle agit l'agent, lue au début de la mutation. */
813
837
  request;
814
838
  /** Jeton avec lequel agit l'agent. */
@@ -1690,6 +1714,7 @@ export class Mutation {
1690
1714
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1691
1715
  .run(request.id, request.authorId, request.targetSpaceId, request.kind, request.contextTaskId, request.contextIdeaId, request.text, request.status, request.createdAt, request.updatedAt);
1692
1716
  this.createdRequestIds.add(request.id);
1717
+ this.pendingRequestIds.push(request.id);
1693
1718
  this.touchRequest(request);
1694
1719
  return request;
1695
1720
  }
@@ -1735,6 +1760,7 @@ export class Mutation {
1735
1760
  throw new InvariantError(`Request ${id} is ${current.status}: only a processing request can be released.`);
1736
1761
  this.db.prepare("UPDATE agent_requests SET status = 'pending', claimed_at = NULL, claimed_by_token_id = NULL, updated_at = ? WHERE id = ?").run(this.now, id);
1737
1762
  const released = this.store.getAgentRequest(id);
1763
+ this.pendingRequestIds.push(id);
1738
1764
  this.touchRequest(released);
1739
1765
  return released;
1740
1766
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Présence des veilleurs de notifications, par jeton d'agent.
3
+ *
4
+ * Un veilleur enchaîne des attentes longues sur `GET /api/agent/requests/wait`.
5
+ * Le registre rend sa présence observable : `enable_notifications` répond
6
+ * « déjà armé », la page Agent de la GUI affiche « à l'écoute ».
7
+ *
8
+ * État de connexion, donc volatile : il vit en mémoire du processus du site et
9
+ * disparaît avec lui.
10
+ */
11
+ /**
12
+ * Délai de grâce entre deux attentes d'un même veilleur : le jeton reste
13
+ * « à l'écoute » pendant le court intervalle où aucune attente n'est ouverte.
14
+ */
15
+ export declare const WATCHER_GRACE_MS: number;
16
+ export interface WatcherStatus {
17
+ armed: boolean;
18
+ /** Début de la série d'attentes en cours, null sans veilleur. */
19
+ since: string | null;
20
+ /** Dernière activité connue d'un veilleur de ce jeton, null si aucune. */
21
+ lastSeen: string | null;
22
+ }
23
+ export declare class WatcherRegistry {
24
+ private readonly now;
25
+ private readonly presence;
26
+ constructor(now?: () => number);
27
+ /** Déclare une attente de veilleur du jeton `tokenId`. La fonction rendue la clôt ; elle doit toujours être appelée. */
28
+ begin(tokenId: string): () => void;
29
+ status(tokenId: string): WatcherStatus;
30
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Présence des veilleurs de notifications, par jeton d'agent.
3
+ *
4
+ * Un veilleur enchaîne des attentes longues sur `GET /api/agent/requests/wait`.
5
+ * Le registre rend sa présence observable : `enable_notifications` répond
6
+ * « déjà armé », la page Agent de la GUI affiche « à l'écoute ».
7
+ *
8
+ * État de connexion, donc volatile : il vit en mémoire du processus du site et
9
+ * disparaît avec lui.
10
+ */
11
+ /**
12
+ * Délai de grâce entre deux attentes d'un même veilleur : le jeton reste
13
+ * « à l'écoute » pendant le court intervalle où aucune attente n'est ouverte.
14
+ */
15
+ export const WATCHER_GRACE_MS = 2 * 60 * 1000;
16
+ export class WatcherRegistry {
17
+ now;
18
+ presence = new Map();
19
+ constructor(now = Date.now) {
20
+ this.now = now;
21
+ }
22
+ /** Déclare une attente de veilleur du jeton `tokenId`. La fonction rendue la clôt ; elle doit toujours être appelée. */
23
+ begin(tokenId) {
24
+ const now = this.now();
25
+ const current = this.presence.get(tokenId);
26
+ const continuing = current !== undefined && (current.inflight > 0 || now - current.lastSeen <= WATCHER_GRACE_MS);
27
+ this.presence.set(tokenId, continuing ? { ...current, inflight: current.inflight + 1, lastSeen: now } : { inflight: 1, since: now, lastSeen: now });
28
+ let released = false;
29
+ return () => {
30
+ if (released)
31
+ return;
32
+ released = true;
33
+ const active = this.presence.get(tokenId);
34
+ if (!active)
35
+ return;
36
+ this.presence.set(tokenId, { ...active, inflight: Math.max(0, active.inflight - 1), lastSeen: this.now() });
37
+ };
38
+ }
39
+ status(tokenId) {
40
+ const entry = this.presence.get(tokenId);
41
+ if (!entry)
42
+ return { armed: false, since: null, lastSeen: null };
43
+ const armed = entry.inflight > 0 || this.now() - entry.lastSeen <= WATCHER_GRACE_MS;
44
+ if (!armed) {
45
+ this.presence.delete(tokenId);
46
+ return { armed: false, since: null, lastSeen: new Date(entry.lastSeen).toISOString() };
47
+ }
48
+ return { armed: true, since: new Date(entry.since).toISOString(), lastSeen: new Date(entry.lastSeen).toISOString() };
49
+ }
50
+ }
package/dist/src/index.js CHANGED
@@ -19,6 +19,10 @@ Usage :
19
19
  (dossier <fichier>.attachments).
20
20
  mcp-organizer --claude-setup-mcp [--force] --url=<URL du site> --token=<jeton>
21
21
  Écrit l'entrée du mode MCP dans ./.mcp.json.
22
+ mcp-organizer --watch <id du jeton>
23
+ Veilleur de notifications : une ligne par demande passée en attente.
24
+ Lancé par l'outil Monitor de l'agent, avec la commande que rend
25
+ l'outil enable_notifications.
22
26
  mcp-organizer --version Affiche la version.
23
27
  mcp-organizer --help Affiche cette aide.
24
28
 
@@ -50,6 +54,12 @@ async function main() {
50
54
  const { runSetupMcp } = await import("./cli/setup-mcp.js");
51
55
  process.exit(runSetupMcp(argv, process.cwd()));
52
56
  }
57
+ // Le veilleur lit l'URL du site et le jeton dans le relais déposé par enable_notifications.
58
+ const watchIndex = argv.indexOf("--watch");
59
+ if (watchIndex !== -1) {
60
+ const { runWatchMode } = await import("./cli/watch.js");
61
+ process.exit(await runWatchMode(argv[watchIndex + 1]));
62
+ }
53
63
  const rootDir = findProjectRoot(path.dirname(fileURLToPath(import.meta.url)));
54
64
  const siteCommand = SITE_COMMANDS.some((flag) => argv.includes(flag));
55
65
  // Les commandes du site ouvrent la base : better-sqlite3 doit avoir son module natif.
@@ -1,9 +1,11 @@
1
+ import type { z } from "zod";
2
+ import { type AgentEnvelope, type WaitRequestsData } from "../../shared/schemas/agent-tools.schema.js";
1
3
  import type { ToolHttpRequest } from "./tools.js";
2
4
  /**
3
5
  * Client HTTP de l'API agent du site : seul point de sortie réseau du mode
4
6
  * MCP. Chaque appel porte le jeton dans `Authorization: Bearer`.
5
7
  */
6
- /** Délai maximal d'un appel au site. */
8
+ /** Délai maximal d'un appel au site, hors attente longue. */
7
9
  export declare const REQUEST_TIMEOUT_MS = 30000;
8
10
  /** Échec d'un appel : refus du site (avec son message) ou site injoignable. */
9
11
  export declare class SiteError extends Error {
@@ -20,4 +22,17 @@ export declare class OrganizerSiteClient {
20
22
  constructor(connection: SiteConnection);
21
23
  /** Exécute la requête d'un outil et renvoie le texte rédigé pour l'agent. */
22
24
  call(request: ToolHttpRequest): Promise<string>;
25
+ /**
26
+ * Attente longue des demandes qui passent en attente (`GET requests/wait`) ;
27
+ * le délai de l'appel couvre la durée de l'attente.
28
+ */
29
+ waitForRequests(query: {
30
+ timeout_seconds: number;
31
+ since?: string;
32
+ watcher?: boolean;
33
+ }): Promise<WaitRequestsData>;
34
+ /** Données structurées d'une réponse, validées par `schema`. */
35
+ parseData<S extends z.ZodType>(schema: S, data: unknown): z.infer<S>;
36
+ /** Exécute une requête de l'API agent et renvoie sa réponse : texte rédigé pour l'agent et données structurées. */
37
+ envelope(request: ToolHttpRequest, timeoutMs?: number): Promise<AgentEnvelope>;
23
38
  }
@@ -1,9 +1,9 @@
1
- import { AgentEnvelopeSchema, AgentErrorSchema } from "../../shared/schemas/agent-tools.schema.js";
1
+ import { AgentEnvelopeSchema, AgentErrorSchema, WaitRequestsDataSchema } from "../../shared/schemas/agent-tools.schema.js";
2
2
  /**
3
3
  * Client HTTP de l'API agent du site : seul point de sortie réseau du mode
4
4
  * MCP. Chaque appel porte le jeton dans `Authorization: Bearer`.
5
5
  */
6
- /** Délai maximal d'un appel au site. */
6
+ /** Délai maximal d'un appel au site, hors attente longue. */
7
7
  export const REQUEST_TIMEOUT_MS = 30_000;
8
8
  /** Échec d'un appel : refus du site (avec son message) ou site injoignable. */
9
9
  export class SiteError extends Error {
@@ -33,6 +33,31 @@ export class OrganizerSiteClient {
33
33
  }
34
34
  /** Exécute la requête d'un outil et renvoie le texte rédigé pour l'agent. */
35
35
  async call(request) {
36
+ return (await this.envelope(request)).text;
37
+ }
38
+ /**
39
+ * Attente longue des demandes qui passent en attente (`GET requests/wait`) ;
40
+ * le délai de l'appel couvre la durée de l'attente.
41
+ */
42
+ async waitForRequests(query) {
43
+ const params = { timeout_seconds: String(query.timeout_seconds) };
44
+ if (query.since !== undefined)
45
+ params.since = query.since;
46
+ if (query.watcher)
47
+ params.watcher = "true";
48
+ const envelope = await this.envelope({ method: "GET", path: "requests/wait", query: params, body: undefined }, query.timeout_seconds * 1000 + REQUEST_TIMEOUT_MS);
49
+ return this.parseData(WaitRequestsDataSchema, envelope.data);
50
+ }
51
+ /** Données structurées d'une réponse, validées par `schema`. */
52
+ parseData(schema, data) {
53
+ const parsed = schema.safeParse(data);
54
+ if (!parsed.success) {
55
+ throw new SiteError(`The organizer site at ${this.connection.url} sent an unexpected answer. Check that the site runs the same version of @imenam/mcp-organizer.`);
56
+ }
57
+ return parsed.data;
58
+ }
59
+ /** Exécute une requête de l'API agent et renvoie sa réponse : texte rédigé pour l'agent et données structurées. */
60
+ async envelope(request, timeoutMs = REQUEST_TIMEOUT_MS) {
36
61
  const url = new URL(`${this.connection.url}/api/agent/${request.path}`);
37
62
  for (const [name, value] of Object.entries(request.query))
38
63
  url.searchParams.set(name, value);
@@ -48,7 +73,7 @@ export class OrganizerSiteClient {
48
73
  body: request.body === undefined ? undefined : JSON.stringify(request.body),
49
74
  // Une redirection n'est jamais suivie : le jeton ne part que vers ORGANIZER_URL.
50
75
  redirect: "manual",
51
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
76
+ signal: AbortSignal.timeout(timeoutMs),
52
77
  });
53
78
  }
54
79
  catch (error) {
@@ -76,6 +101,6 @@ export class OrganizerSiteClient {
76
101
  if (!envelope.success) {
77
102
  throw new SiteError(`The organizer site at ${this.connection.url} sent an unexpected answer. Check ORGANIZER_URL and that the site runs the same version of @imenam/mcp-organizer.`);
78
103
  }
79
- return envelope.data.text;
104
+ return envelope.data;
80
105
  }
81
106
  }
@@ -0,0 +1,30 @@
1
+ import { type AgentRequestSummary } from "../../shared/schemas/agent-tools.schema.js";
2
+ import type { OrganizerSiteClient, SiteConnection } from "./client.js";
3
+ import { type ToolDefinition } from "./tools.js";
4
+ /**
5
+ * Outils de notification, exécutés par le mode MCP lui-même.
6
+ *
7
+ * `enable_notifications` fonctionne de deux façons. En local, il dépose le
8
+ * relais du veilleur et rend l'appel `Monitor` qui lance `--watch`. Derrière
9
+ * le relais de mcp-http-gateway, qui remplit l'argument réservé
10
+ * `_gateway_watch`, il rend une spécification de veille
11
+ * (`_meta["gateway/watch"]`) : le relais lance alors son propre veilleur, qui
12
+ * appelle `wait_for_requests` en boucle à travers la gateway.
13
+ */
14
+ /** Clés de la convention de veille de mcp-http-gateway (voir son gateway-watch.js). */
15
+ export declare const WATCH_ARG = "_gateway_watch";
16
+ /** Résultat d'un outil de notification : texte pour l'agent et métadonnées pour le relais. */
17
+ export interface NotificationToolResult {
18
+ text: string;
19
+ meta?: Record<string, unknown>;
20
+ }
21
+ /** Ligne d'une demande : une seule ligne, lisible telle quelle dans la notification. */
22
+ export declare function formatRequestEvent(request: AgentRequestSummary): string;
23
+ /** Durée maximale d'un `Monitor` côté hôte. */
24
+ export declare const MONITOR_TIMEOUT_MS = 1800000;
25
+ export declare const ENABLE_NOTIFICATIONS_TOOL: ToolDefinition;
26
+ export declare const WAIT_FOR_REQUESTS_TOOL: ToolDefinition;
27
+ /** Commande du veilleur du jeton `tokenId`. */
28
+ export declare function watchCommand(tokenId: string): string;
29
+ export declare function enableNotifications(client: OrganizerSiteClient, connection: SiteConnection, args: Record<string, unknown>): Promise<NotificationToolResult>;
30
+ export declare function waitForRequests(client: OrganizerSiteClient, args: Record<string, unknown>): Promise<NotificationToolResult>;
@@ -0,0 +1,140 @@
1
+ import { MAX_WAIT_SECONDS, NotificationsDataSchema } from "../../shared/schemas/agent-tools.schema.js";
2
+ import { ToolArgumentError } from "./tools.js";
3
+ import { writeHandoff } from "./watch-handoff.js";
4
+ /**
5
+ * Outils de notification, exécutés par le mode MCP lui-même.
6
+ *
7
+ * `enable_notifications` fonctionne de deux façons. En local, il dépose le
8
+ * relais du veilleur et rend l'appel `Monitor` qui lance `--watch`. Derrière
9
+ * le relais de mcp-http-gateway, qui remplit l'argument réservé
10
+ * `_gateway_watch`, il rend une spécification de veille
11
+ * (`_meta["gateway/watch"]`) : le relais lance alors son propre veilleur, qui
12
+ * appelle `wait_for_requests` en boucle à travers la gateway.
13
+ */
14
+ /** Clés de la convention de veille de mcp-http-gateway (voir son gateway-watch.js). */
15
+ export const WATCH_ARG = "_gateway_watch";
16
+ const WATCH_META = "gateway/watch";
17
+ const EVENTS_META = "gateway/events";
18
+ /** Longueur maximale de l'extrait du texte d'une demande dans sa ligne. */
19
+ const EXCERPT_LENGTH = 120;
20
+ /** Ligne d'une demande : une seule ligne, lisible telle quelle dans la notification. */
21
+ export function formatRequestEvent(request) {
22
+ const text = request.text.replace(/\s+/g, " ").trim();
23
+ const excerpt = text.length > EXCERPT_LENGTH ? `${text.slice(0, EXCERPT_LENGTH - 1)}…` : text;
24
+ const context = request.contextTask ? ` · ${request.contextTask.key}` : "";
25
+ return `[organizer] ${request.kind} · ${request.author.name} — "${excerpt}"${context} (${request.id})`;
26
+ }
27
+ /** Durée maximale d'un `Monitor` côté hôte. */
28
+ export const MONITOR_TIMEOUT_MS = 1_800_000;
29
+ const PACKAGE_NAME = "@imenam/mcp-organizer";
30
+ export const ENABLE_NOTIFICATIONS_TOOL = {
31
+ name: "enable_notifications",
32
+ description: "Get notified in real time of the requests the members of your space send to the AI, without polling the queue. Returns immediately: it blocks nothing and starts nothing on its own. It hands you the exact Monitor call to make right after — arming that watcher is what actually delivers notifications, and until you do it no request will reach you. Call this once at the start of a session; then keep working, each new pending request interrupts you on its own. The host stops the watcher after 30 minutes at most: re-arm it with the same Monitor call each time it expires.",
33
+ inputSchema: {
34
+ type: "object",
35
+ properties: {
36
+ [WATCH_ARG]: {
37
+ type: "object",
38
+ description: "Filled in by the mcp-http-gateway relay, never by the agent: the relay will run the watcher and needs a watch specification instead of a local command.",
39
+ },
40
+ },
41
+ additionalProperties: false,
42
+ },
43
+ };
44
+ export const WAIT_FOR_REQUESTS_TOOL = {
45
+ name: "wait_for_requests",
46
+ description: "Block until at least one request of your space becomes pending (created, or released by a member), or until the timeout. Returns the new pending requests (none on timeout) and a cursor: pass it to the next call to get exactly what became pending since. It is the waiting tool of the notification watcher; to stay reachable, prefer enable_notifications.",
47
+ inputSchema: {
48
+ type: "object",
49
+ properties: {
50
+ cursor: {
51
+ type: "string",
52
+ description: "Cursor returned by the previous call. Without it, only requests that become pending after the call starts are returned.",
53
+ },
54
+ timeout_seconds: { type: "integer", minimum: 1, maximum: MAX_WAIT_SECONDS, description: `Maximum wait, in seconds (1-${MAX_WAIT_SECONDS}, defaults to 30).` },
55
+ watcher: {
56
+ type: "boolean",
57
+ description: "Set by the notification watcher: the wait counts as the presence of this token's watcher, shown as listening in the web app.",
58
+ },
59
+ },
60
+ additionalProperties: false,
61
+ },
62
+ };
63
+ /** Commande du veilleur du jeton `tokenId`. */
64
+ export function watchCommand(tokenId) {
65
+ return `npx -y ${PACKAGE_NAME} --watch ${tokenId}`;
66
+ }
67
+ export async function enableNotifications(client, connection, args) {
68
+ for (const name of Object.keys(args)) {
69
+ if (name !== WATCH_ARG)
70
+ throw new ToolArgumentError(`Invalid arguments — ${name}: enable_notifications takes no argument.`);
71
+ }
72
+ const envelope = await client.envelope({ method: "GET", path: "notifications", query: {}, body: undefined });
73
+ const { token, space, pendingCount, watcher, cursor } = client.parseData(NotificationsDataSchema, envelope.data);
74
+ if (args[WATCH_ARG] !== undefined) {
75
+ return {
76
+ text: `Watch specification for the mcp-http-gateway relay: requests of space "${space.name}" for token "${token.name}".`,
77
+ meta: {
78
+ [WATCH_META]: {
79
+ tool: WAIT_FOR_REQUESTS_TOOL.name,
80
+ arguments: { watcher: true },
81
+ cursor,
82
+ description: "New requests for the AI in the organizer",
83
+ },
84
+ },
85
+ };
86
+ }
87
+ writeHandoff({ tokenId: token.id, url: connection.url, token: connection.token });
88
+ const command = watchCommand(token.id);
89
+ if (watcher.armed) {
90
+ const text = [
91
+ `Notifications are already live for token "${token.name}" on space "${space.name}" (watcher armed since ${watcher.since}).`,
92
+ "Nothing to do: keep working, new requests will interrupt you on their own.",
93
+ "Do not arm a second watcher — you would get every request twice.",
94
+ "Only exception: if the host just told you your watcher expired or stopped, re-arm it",
95
+ `with the same Monitor call (command \`${command}\`, timeout_ms ${MONITOR_TIMEOUT_MS}).`,
96
+ ].join("\n");
97
+ return { text };
98
+ }
99
+ const lines = [
100
+ `Notifications enabled for token "${token.name}" on space "${space.name}".`,
101
+ "",
102
+ "Last step — call the Monitor tool now, with exactly these arguments:",
103
+ ` command: ${command}`,
104
+ " description: New requests for the AI in the organizer",
105
+ ` timeout_ms: ${MONITOR_TIMEOUT_MS}`,
106
+ "",
107
+ "Until that watcher is armed, nothing will reach you: no request will be announced.",
108
+ "Once it is, keep working normally — each request that becomes pending shows up on its own,",
109
+ "even while you are idle. One line per request; process it with claim_request.",
110
+ "",
111
+ "The host stops every monitor after 30 minutes at most. Each time it tells you this",
112
+ "watcher expired, call Monitor again right away with the same arguments — do not call",
113
+ "enable_notifications again. Skip that and notifications stop for good.",
114
+ ];
115
+ if (pendingCount > 0) {
116
+ lines.push("", `${pendingCount} request(s) are already pending. Only requests that become pending AFTER the`, "watcher starts are announced — process the backlog with list_requests.");
117
+ }
118
+ return { text: lines.join("\n") };
119
+ }
120
+ export async function waitForRequests(client, args) {
121
+ for (const name of Object.keys(args)) {
122
+ if (!(name in WAIT_FOR_REQUESTS_TOOL.inputSchema.properties))
123
+ throw new ToolArgumentError(`Invalid arguments — ${name}: unknown argument. Check the tool's input schema.`);
124
+ }
125
+ const { cursor, timeout_seconds: timeout, watcher } = args;
126
+ if (cursor !== undefined && typeof cursor !== "string")
127
+ throw new ToolArgumentError("Invalid arguments — cursor: expected the string returned by the previous call.");
128
+ if (timeout !== undefined && (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 1 || timeout > MAX_WAIT_SECONDS)) {
129
+ throw new ToolArgumentError(`Invalid arguments — timeout_seconds: expected an integer from 1 to ${MAX_WAIT_SECONDS}.`);
130
+ }
131
+ if (watcher !== undefined && typeof watcher !== "boolean")
132
+ throw new ToolArgumentError("Invalid arguments — watcher: expected a boolean.");
133
+ const seconds = timeout ?? 30;
134
+ const result = await client.waitForRequests({ timeout_seconds: seconds, since: cursor, watcher: watcher === true });
135
+ const lines = result.requests.map(formatRequestEvent);
136
+ const text = lines.length === 0
137
+ ? `No new pending request in "${result.space.name}" after ${seconds}s. Cursor: ${result.cursor}`
138
+ : `${lines.length} new pending request(s) in "${result.space.name}":\n${lines.join("\n")}\nCursor: ${result.cursor}\n\nNext: call claim_request with the id of the oldest request.`;
139
+ return { text, meta: { [EVENTS_META]: { cursor: result.cursor, lines } } };
140
+ }
@@ -1,6 +1,6 @@
1
1
  import { type SiteConnection } from "./client.js";
2
2
  /** Présentation du serveur transmise au client MCP : concepts et déroulé. */
3
- export declare const INSTRUCTIONS = "mcp-organizer connects you to an organizer site: a multi-user task manager where people organize tasks in a web app and queue requests for the AI. You, the connected agent, process those requests when the user asks you to. The site never calls an LLM: you are the intelligence.\n\nYour token covers exactly one space, with the rights of the user who created the token. Every tool works on that space.\n\nConcepts:\n- A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.\n- A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).\n- A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply) or failed (with the reason).\n- A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.\n- The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.\n\nWork loop, when the user asks you to process the queue:\n1. list_requests to see the pending requests of your space.\n2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, task tree, members, recent ideas). get_context shows the space at any time.\n3. Read what you need with get_task and search_tasks.\n4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea \u2014 always passing the request_id. Each write is one undoable action of the batch.\n5. complete_request with a short reply in the author's language (or fail_request with the reason), then go back to step 1 until no request is pending.\nNothing arrives on its own: there is no waiting tool. When the queue is empty, tell the user.\n\nHow to handle each kind of request:\n- **idea**: classify it. If it belongs to an existing task or sub-task, attach it there (sub-task, checklist item or comment). If it is actionable and important enough, create a task (or sub-task) with a fitting priority. Otherwise, put it in the idea box with create_idea. Prefer existing tasks over duplicates.\n- **test_review**: feed the tester's findings back into the existing tasks (status, checklist, comments, priority of the affected tasks), or create a task for each problem that has none.\n- **remark** and **message**: do whatever is useful \u2014 answer, update or create tasks, comment \u2014 and say what you did in the reply.\n- **idea_promotion**: turn the context idea into a well-formed task with promote_idea.\n\nRules: write titles, descriptions and replies in the language of the users; keep the reply short and factual. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.";
3
+ export declare const INSTRUCTIONS = "mcp-organizer connects you to an organizer site: a multi-user task manager where people organize tasks in a web app and queue requests for the AI. You, the connected agent, process those requests when the user asks you to. The site never calls an LLM: you are the intelligence.\n\nYour token covers exactly one space, with the rights of the user who created the token. Every tool works on that space.\n\nConcepts:\n- A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.\n- A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).\n- A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply) or failed (with the reason).\n- A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.\n- The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.\n\nWork loop, when the user asks you to process the queue:\n1. list_requests to see the pending requests of your space.\n2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, task tree, members, recent ideas). get_context shows the space at any time.\n3. Read what you need with get_task and search_tasks.\n4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea \u2014 always passing the request_id. Each write is one undoable action of the batch.\n5. complete_request with a short reply in the author's language (or fail_request with the reason), then go back to step 1 until no request is pending.\nWhen the queue is empty, tell the user.\n\nNotifications: call enable_notifications once at the start of the session and arm the watcher it hands you with Monitor, whatever the command (behind mcp-http-gateway, the gateway relay answers in place of this server and gives its own watcher command). Each request that becomes pending in your space then arrives on its own as one line (kind, author, excerpt, request id), even while you are idle: process it with the work loop above, starting with claim_request. The host stops that watcher after 30 minutes at most: each time it tells you the watcher expired, re-arm it at once with the same Monitor call; otherwise notifications stop for good. A line \"notifications stopped\" means the site refused the token, and a line \"[gateway-watch] \u2026 la veille \u00E9choue\" means the gateway watcher keeps failing: tell the user. wait_for_requests is the waiting tool of the watcher: you do not need to call it.\n\nHow to handle each kind of request:\n- **idea**: classify it. If it belongs to an existing task or sub-task, attach it there (sub-task, checklist item or comment). If it is actionable and important enough, create a task (or sub-task) with a fitting priority. Otherwise, put it in the idea box with create_idea. Prefer existing tasks over duplicates.\n- **test_review**: feed the tester's findings back into the existing tasks (status, checklist, comments, priority of the affected tasks), or create a task for each problem that has none.\n- **remark** and **message**: do whatever is useful \u2014 answer, update or create tasks, comment \u2014 and say what you did in the reply.\n- **idea_promotion**: turn the context idea into a well-formed task with promote_idea.\n\nRules: write titles, descriptions and replies in the language of the users; keep the reply short and factual. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.";
4
4
  /**
5
5
  * Connexion au site d'après `ORGANIZER_URL` et `ORGANIZER_TOKEN` ; une valeur
6
6
  * absente ou invalide, ou une URL http vers une autre machine, est une `ConfigError`.
@@ -6,32 +6,36 @@ import { createLogger, setupLogging } from "../core/logger.js";
6
6
  import { ConfigError } from "../core/errors.js";
7
7
  import { OrganizerSiteClient, SiteError } from "./client.js";
8
8
  import { AGENT_TOOLS, ToolArgumentError, findAgentTool, toolHttpRequest } from "./tools.js";
9
+ import { ENABLE_NOTIFICATIONS_TOOL, WAIT_FOR_REQUESTS_TOOL, enableNotifications, waitForRequests } from "./notifications.js";
10
+ import { removeOwnHandoffs } from "./watch-handoff.js";
9
11
  /** Présentation du serveur transmise au client MCP : concepts et déroulé. */
10
- export const INSTRUCTIONS = `mcp-organizer connects you to an organizer site: a multi-user task manager where people organize tasks in a web app and queue requests for the AI. You, the connected agent, process those requests when the user asks you to. The site never calls an LLM: you are the intelligence.
11
-
12
- Your token covers exactly one space, with the rights of the user who created the token. Every tool works on that space.
13
-
14
- Concepts:
15
- - A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.
16
- - A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).
17
- - A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply) or failed (with the reason).
18
- - A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.
19
- - The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.
20
-
21
- Work loop, when the user asks you to process the queue:
22
- 1. list_requests to see the pending requests of your space.
23
- 2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, task tree, members, recent ideas). get_context shows the space at any time.
24
- 3. Read what you need with get_task and search_tasks.
25
- 4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea — always passing the request_id. Each write is one undoable action of the batch.
26
- 5. complete_request with a short reply in the author's language (or fail_request with the reason), then go back to step 1 until no request is pending.
27
- Nothing arrives on its own: there is no waiting tool. When the queue is empty, tell the user.
28
-
29
- How to handle each kind of request:
30
- - **idea**: classify it. If it belongs to an existing task or sub-task, attach it there (sub-task, checklist item or comment). If it is actionable and important enough, create a task (or sub-task) with a fitting priority. Otherwise, put it in the idea box with create_idea. Prefer existing tasks over duplicates.
31
- - **test_review**: feed the tester's findings back into the existing tasks (status, checklist, comments, priority of the affected tasks), or create a task for each problem that has none.
32
- - **remark** and **message**: do whatever is useful — answer, update or create tasks, comment — and say what you did in the reply.
33
- - **idea_promotion**: turn the context idea into a well-formed task with promote_idea.
34
-
12
+ export const INSTRUCTIONS = `mcp-organizer connects you to an organizer site: a multi-user task manager where people organize tasks in a web app and queue requests for the AI. You, the connected agent, process those requests when the user asks you to. The site never calls an LLM: you are the intelligence.
13
+
14
+ Your token covers exactly one space, with the rights of the user who created the token. Every tool works on that space.
15
+
16
+ Concepts:
17
+ - A **space** holds tasks and an idea box. A user's **personal space** is private; a **shared space** has one owner and members.
18
+ - A **task** has a title, a markdown description, a status (todo, doing, review, done), a priority (low, medium, high, critical), assignees and tags. Tasks nest on two levels: task > sub-task > sub-sub-task. A task is either standard (with a checklist) or a test (with checkpoints that each tester marks ok, ko, blocked or untested).
19
+ - A **request** is something a member of your space asked the AI: an idea, a remark, a test review, a message or an idea promotion. It is pending, then processing once you claim it (only your token can then act for it), then done (with your reply) or failed (with the reason).
20
+ - A **batch** is the set of actions you perform for one request. Every action is logged with its before and after state and with your token, and users can undo one action or the whole batch.
21
+ - The **scope** of your work is the space of your token: you see and process the requests of all its members, and you never act outside it.
22
+
23
+ Work loop, when the user asks you to process the queue:
24
+ 1. list_requests to see the pending requests of your space.
25
+ 2. claim_request on the oldest one: it becomes processing for you and you get its context (text, author, context task, task tree, members, recent ideas). get_context shows the space at any time.
26
+ 3. Read what you need with get_task and search_tasks.
27
+ 4. Act with create_task, update_task, set_assignees, set_tags, edit_checklist, add_comment, create_idea, update_idea, promote_idea — always passing the request_id. Each write is one undoable action of the batch.
28
+ 5. complete_request with a short reply in the author's language (or fail_request with the reason), then go back to step 1 until no request is pending.
29
+ When the queue is empty, tell the user.
30
+
31
+ Notifications: call enable_notifications once at the start of the session and arm the watcher it hands you with Monitor, whatever the command (behind mcp-http-gateway, the gateway relay answers in place of this server and gives its own watcher command). Each request that becomes pending in your space then arrives on its own as one line (kind, author, excerpt, request id), even while you are idle: process it with the work loop above, starting with claim_request. The host stops that watcher after 30 minutes at most: each time it tells you the watcher expired, re-arm it at once with the same Monitor call; otherwise notifications stop for good. A line "notifications stopped" means the site refused the token, and a line "[gateway-watch] … la veille échoue" means the gateway watcher keeps failing: tell the user. wait_for_requests is the waiting tool of the watcher: you do not need to call it.
32
+
33
+ How to handle each kind of request:
34
+ - **idea**: classify it. If it belongs to an existing task or sub-task, attach it there (sub-task, checklist item or comment). If it is actionable and important enough, create a task (or sub-task) with a fitting priority. Otherwise, put it in the idea box with create_idea. Prefer existing tasks over duplicates.
35
+ - **test_review**: feed the tester's findings back into the existing tasks (status, checklist, comments, priority of the affected tasks), or create a task for each problem that has none.
36
+ - **remark** and **message**: do whatever is useful — answer, update or create tasks, comment — and say what you did in the reply.
37
+ - **idea_promotion**: turn the context idea into a well-formed task with promote_idea.
38
+
35
39
  Rules: write titles, descriptions and replies in the language of the users; keep the reply short and factual. Errors tell you what to do next; an error about the token (missing, revoked, expired, owner no longer a member) cannot be fixed by retrying: tell the user.`;
36
40
  /** Hôtes de la machine locale, seuls admis en http. */
37
41
  const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -80,9 +84,26 @@ export async function runMcpMode() {
80
84
  const logger = createLogger("mcp");
81
85
  const client = new OrganizerSiteClient(connection);
82
86
  const server = new Server({ name: "mcp-organizer", version: APP_VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
83
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: AGENT_TOOLS.map((tool) => tool.definition) }));
87
+ // Outils exécutés par le mode MCP lui-même : leur résultat peut porter des métadonnées pour le relais de mcp-http-gateway.
88
+ const notificationTools = {
89
+ [ENABLE_NOTIFICATIONS_TOOL.name]: (args) => enableNotifications(client, connection, args),
90
+ [WAIT_FOR_REQUESTS_TOOL.name]: (args) => waitForRequests(client, args),
91
+ };
92
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [...AGENT_TOOLS.map((tool) => tool.definition), ENABLE_NOTIFICATIONS_TOOL, WAIT_FOR_REQUESTS_TOOL] }));
84
93
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
85
94
  const { name, arguments: args } = request.params;
95
+ const notificationTool = notificationTools[name];
96
+ if (notificationTool) {
97
+ try {
98
+ const result = await notificationTool((args ?? {}));
99
+ return { content: [{ type: "text", text: result.text }], ...(result.meta ? { _meta: result.meta } : {}) };
100
+ }
101
+ catch (error) {
102
+ if (!(error instanceof SiteError) && !(error instanceof ToolArgumentError))
103
+ logger.error(`Tool ${name} failed: ${error?.stack ?? error}`);
104
+ return errorResult(error?.message ?? String(error));
105
+ }
106
+ }
86
107
  const tool = findAgentTool(name);
87
108
  if (!tool)
88
109
  return errorResult(`Unknown tool "${name}". Call tools/list to get the available tools.`);
@@ -96,6 +117,11 @@ export async function runMcpMode() {
96
117
  return errorResult(error?.message ?? String(error));
97
118
  }
98
119
  });
120
+ // Le relais du veilleur porte le jeton : il ne survit pas au mode MCP qui l'a écrit.
121
+ process.on("exit", removeOwnHandoffs);
122
+ for (const signal of ["SIGINT", "SIGTERM"]) {
123
+ process.on(signal, () => process.exit(0));
124
+ }
99
125
  await server.connect(new StdioServerTransport());
100
126
  logger.info(`MCP server running on stdio (version ${APP_VERSION}, site: ${connection.url})`);
101
127
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Relais entre la session MCP et son veilleur de notifications.
3
+ *
4
+ * Le veilleur est lancé par l'agent via l'outil `Monitor` de l'hôte : c'est un
5
+ * processus du shell de la session, pas un enfant du mode MCP. Il n'hérite donc
6
+ * pas du bloc `env` du `.mcp.json` et n'a ni URL du site ni jeton. Les passer sur
7
+ * la ligne de commande les afficherait dans la conversation : ils transitent par
8
+ * un fichier en 0600, que seul l'identifiant du jeton (pas sa valeur) permet de
9
+ * retrouver.
10
+ *
11
+ * Le fichier est écrit par `enable_notifications`, jamais au démarrage, et retiré
12
+ * à l'arrêt du mode MCP qui l'a écrit en dernier.
13
+ */
14
+ export interface Handoff {
15
+ /** Identifiant du jeton d'agent. */
16
+ tokenId: string;
17
+ url: string;
18
+ /** Valeur du jeton. */
19
+ token: string;
20
+ /** Processus du mode MCP qui a écrit le relais. */
21
+ pid: number;
22
+ /** Horodatage d'écriture, qui sert à purger les relais abandonnés. */
23
+ writtenAt: string;
24
+ }
25
+ /** Répertoire des relais : `<ORGANIZER_STATE_DIR>/watch`, ou `~/.mcp-organizer/watch`. */
26
+ export declare function handoffDir(): string;
27
+ /** Fichier du relais d'un jeton, nommé d'après le hachage de son identifiant. */
28
+ export declare function handoffPath(tokenId: string): string;
29
+ export declare function writeHandoff(handoff: Omit<Handoff, "pid" | "writtenAt">): string;
30
+ /** Relais du jeton `tokenId`, ou null s'il n'existe pas ou ne concerne pas ce jeton. */
31
+ export declare function readHandoff(tokenId: string): Handoff | null;
32
+ /** Supprime le relais du jeton s'il a été écrit en dernier par ce processus. */
33
+ export declare function removeHandoff(tokenId: string): void;
34
+ /** Supprime les relais écrits en dernier par ce processus. Synchrone : appelable sur `exit`. */
35
+ export declare function removeOwnHandoffs(): void;