@paigy/mcp 0.6.0 → 0.7.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.
@@ -0,0 +1,362 @@
1
+ // ../../packages/schema/dist/index.js
2
+ import { z } from "zod";
3
+ var ContextSchema = z.object({
4
+ title: z.string().min(1).describe("One-line headline of what you need (required, non-empty)."),
5
+ description: z.array(z.string().min(1)).min(1).describe("Semantic chunks of detail (each a standalone, non-empty piece). The user can select chunks to ask you to expand.")
6
+ });
7
+ var OptionSchema = z.object({
8
+ id: z.string(),
9
+ label: z.string(),
10
+ // .describe() flows into the MCP notify_user JSON schema (zodToJsonSchema), so
11
+ // the constraints below are what an agent reads when deciding to use these.
12
+ html: z.string().max(16384).describe(
13
+ "Optional sandboxed HTML/CSS preview for a visual 'pick one' (shown in the option card). Untrusted-sandboxed: NO JavaScript, NO external network or images \u2014 inline CSS and data: URIs only; <=16KB. Use for layout/CSS mockups, tables, diffs. For a hosted image use `image` instead."
14
+ ).optional(),
15
+ image: z.string().url().describe(
16
+ "Optional image URL rendered as the option's preview (plain image, not sandboxed). For agent-generated HTML/CSS mockups, use `html` instead."
17
+ ).optional()
18
+ });
19
+ var VisualSchema = z.object({
20
+ url: z.string().url(),
21
+ label: z.string().optional()
22
+ });
23
+ var AgentSchema = z.object({
24
+ name: z.string()
25
+ });
26
+ var NotifyLevelSchema = z.enum(["inbox", "push", "banner", "call"]);
27
+ var NotifyRequestSchema = z.object({
28
+ context: ContextSchema,
29
+ options: z.array(OptionSchema).optional(),
30
+ visuals: z.array(VisualSchema).optional(),
31
+ agent: AgentSchema,
32
+ /** Git repo the agent is working in ("owner/name"), when applicable. */
33
+ repo: z.string().optional(),
34
+ /** Git branch the agent is on, when applicable. */
35
+ branch: z.string().optional(),
36
+ /** Continue an existing conversation; omitted = start a new thread. */
37
+ threadId: z.string().uuid().optional(),
38
+ createdAt: z.string().datetime(),
39
+ urgency: NotifyLevelSchema.default("inbox").describe(
40
+ "The level you're requesting \u2014 the user's account permissions + session mode can lower it. 'inbox' (default) = sits silently in the inbox for the user to get to. 'push' = a quiet passive push (lands in Notification Center, no sound) \u2014 a gentle heads-up. 'banner' = a time-sensitive banner/lock-screen push with sound (a 'paige') they tap to open \u2014 use when you need them soon-ish but it's not worth ringing them. 'call' = rings the user's phone now (a CallKit voice call) \u2014 use only when you genuinely need them in the moment (blocked and waiting, time-sensitive). context.title is what they see on the banner/ring, so make it specific."
41
+ ),
42
+ /** The request this one was spawned from, for a clarification. */
43
+ parentId: z.string().optional(),
44
+ /** How the user answers the options: pick one (default), pick several, pick & order, or yes/no confirm. */
45
+ select: z.enum(["one", "many", "rank", "confirm"]).default("one"),
46
+ confirmStyle: z.enum(["yesno", "approve"]).default("yesno").describe(
47
+ "Labels for a select:'confirm' paige \u2014 'yesno' (Yes/No) or 'approve' (Approve/Deny). Ignored unless select is 'confirm'."
48
+ )
49
+ });
50
+ var NotifyStatusSchema = z.enum(["pending", "answered", "ignored"]);
51
+ var AgentStateSchema = z.enum(["idle", "in_progress", "completed", "needs_input"]);
52
+ var SetTaskStateSchema = z.object({
53
+ state: z.enum(["in_progress", "completed", "needs_input"])
54
+ });
55
+ var TurnSchema = z.object({
56
+ prompt: z.string(),
57
+ reply: z.string()
58
+ });
59
+ var UserAnswerSchema = z.discriminatedUnion("kind", [
60
+ z.object({ kind: z.literal("option"), optionId: z.string() }),
61
+ z.object({ kind: z.literal("text"), text: z.string() }),
62
+ z.object({ kind: z.literal("ignored") }),
63
+ z.object({ kind: z.literal("multi"), optionIds: z.array(z.string()) }),
64
+ z.object({ kind: z.literal("ranked"), optionIds: z.array(z.string()) }),
65
+ z.object({ kind: z.literal("clarify"), chunks: z.array(z.string()).min(1) }),
66
+ z.object({ kind: z.literal("confirm"), approved: z.boolean() }),
67
+ z.object({ kind: z.literal("turns"), turns: z.array(TurnSchema).min(1) })
68
+ ]);
69
+ var AwaitItemSchema = z.discriminatedUnion("type", [
70
+ z.object({
71
+ type: z.literal("reply"),
72
+ threadId: z.string(),
73
+ notificationId: z.string(),
74
+ answer: UserAnswerSchema
75
+ }),
76
+ z.object({
77
+ type: z.literal("remind"),
78
+ threadId: z.string(),
79
+ notificationId: z.string(),
80
+ remindAt: z.string().datetime({ offset: true }),
81
+ /** Seconds until remindAt, server-computed — pass straight to ScheduleWakeup. */
82
+ remindInSeconds: z.number()
83
+ }),
84
+ z.object({ type: z.literal("idle") })
85
+ ]);
86
+ var CallbackTriggerSchema = z.enum(["on_done", "on_blocked", "scheduled"]);
87
+ var ScheduleCallbackSchema = z.object({
88
+ threadId: z.string().describe("The thread to call back on (from a prior notify_user / reply / request)."),
89
+ trigger: CallbackTriggerSchema,
90
+ dueInSeconds: z.number().int().positive().optional().describe("For 'scheduled' only: how many seconds from now to fire."),
91
+ note: z.string().optional().describe("What to tell the user when you follow up.")
92
+ });
93
+ var PendingRepliesSchema = z.object({
94
+ replies: z.array(
95
+ z.object({ threadId: z.string(), notificationId: z.string(), answer: UserAnswerSchema })
96
+ ),
97
+ pending: z.array(
98
+ z.object({ threadId: z.string(), notificationId: z.string(), createdAt: z.string() })
99
+ ),
100
+ /** User-initiated requests addressed to this agent; act on them and reply via
101
+ * notify_user on the same threadId. Each is returned once (claimed on read). */
102
+ requests: z.array(
103
+ z.object({ threadId: z.string(), notificationId: z.string(), text: z.string(), createdAt: z.string() })
104
+ ),
105
+ /** Callbacks you owe the user that are now DUE (you said you'd follow up when done,
106
+ * if blocked, or at a time that has passed). Re-surfaced every sweep until you
107
+ * fulfill one by calling notify_user on its threadId. */
108
+ owedCallbacks: z.array(
109
+ z.object({ threadId: z.string(), trigger: CallbackTriggerSchema, note: z.string() })
110
+ )
111
+ });
112
+ var NotifyResponseSchema = z.object({
113
+ id: z.string(),
114
+ status: NotifyStatusSchema,
115
+ createdAt: z.string().datetime(),
116
+ answer: UserAnswerSchema.optional(),
117
+ answeredAt: z.string().datetime().optional()
118
+ });
119
+ var UserResponseSchema = z.object({
120
+ requestId: z.string(),
121
+ answer: UserAnswerSchema,
122
+ answeredAt: z.string().datetime()
123
+ });
124
+ var InboxItemSchema = z.object({
125
+ id: z.string(),
126
+ status: NotifyStatusSchema,
127
+ context: ContextSchema,
128
+ options: z.array(OptionSchema).optional(),
129
+ visuals: z.array(VisualSchema).optional(),
130
+ agent: z.string(),
131
+ nickname: z.string(),
132
+ repo: z.string().optional(),
133
+ branch: z.string().optional(),
134
+ createdAt: z.string().datetime(),
135
+ snoozedUntil: z.string().datetime().optional(),
136
+ agentState: AgentStateSchema.default("idle"),
137
+ parentId: z.string().optional(),
138
+ select: z.enum(["one", "many", "rank", "confirm"]).default("one"),
139
+ confirmStyle: z.enum(["yesno", "approve"]).default("yesno").describe(
140
+ "Labels for a select:'confirm' paige \u2014 'yesno' (Yes/No) or 'approve' (Approve/Deny). Ignored unless select is 'confirm'."
141
+ ),
142
+ /** The user's locked-in answer; present only for replied items (GET /api/replied/:id). */
143
+ answer: UserAnswerSchema.optional()
144
+ });
145
+ var SnoozeRequestSchema = z.object({
146
+ requestId: z.string(),
147
+ until: z.string().datetime()
148
+ });
149
+ var PushTokenSchema = z.object({
150
+ voipToken: z.string().min(1).optional(),
151
+ alertToken: z.string().min(1).optional(),
152
+ platform: z.literal("ios")
153
+ });
154
+ var UserSettingsSchema = z.object({
155
+ permissions: z.object({
156
+ call: z.boolean(),
157
+ banner: z.boolean(),
158
+ push: z.boolean()
159
+ }),
160
+ sessionMode: z.enum(["default", "all_calls", "silent"]),
161
+ silentPush: z.boolean(),
162
+ autoCallback: z.boolean()
163
+ });
164
+ var HistoryItemSchema = z.object({
165
+ id: z.string(),
166
+ threadId: z.string(),
167
+ /** 'user' = a request you sent; 'agent' = a notification an agent sent you. */
168
+ initiator: z.enum(["user", "agent"]),
169
+ title: z.string(),
170
+ /** The agent on the other end (nickname). */
171
+ agent: z.string(),
172
+ createdAt: z.string(),
173
+ /** When the agent fetched your request (user→agent only). */
174
+ agentAckedAt: z.string().nullable(),
175
+ /** When you answered the agent's notification (agent→user only). */
176
+ humanAckedAt: z.string().nullable()
177
+ });
178
+ var ConnectionSummarySchema = z.object({
179
+ /** The connection = the agent's token id (used to address a request). */
180
+ id: z.string(),
181
+ agent: z.string(),
182
+ device: z.string().nullable(),
183
+ nickname: z.string(),
184
+ createdAt: z.string().datetime()
185
+ });
186
+ var CreateRequestSchema = z.object({
187
+ /** The connection (token id) to send to, from GET /api/tokens. */
188
+ tokenId: z.string(),
189
+ /** The user's message to the agent. */
190
+ text: z.string().min(1)
191
+ });
192
+ var DeliveryModeSchema = z.enum(["poll", "self_hosted"]);
193
+ var WAKE_EVENT = "wake";
194
+ var wakeChannel = (tokenId) => `wake:${tokenId}`;
195
+ var RegisterDeliverySchema = z.object({ mode: DeliveryModeSchema });
196
+ var OAuthStartSchema = z.object({
197
+ provider: z.enum(["cma"]),
198
+ returnTo: z.string().min(1)
199
+ });
200
+ var SetProviderSchema = z.object({
201
+ provider: z.enum(["cma"]),
202
+ /** Provider-side agent id (e.g. CMA `agent_…`). */
203
+ agentRef: z.string().min(1),
204
+ /** Provider-side environment id (e.g. CMA `env_…`). */
205
+ environmentId: z.string().min(1),
206
+ /** The delegated API key Paigy holds (in Vault) to spawn sessions on the user's behalf. */
207
+ apiKey: z.string().min(1)
208
+ });
209
+ var DeliveryConfigSchema = z.object({
210
+ tokenId: z.string(),
211
+ mode: DeliveryModeSchema,
212
+ /** null when the server has no SUPABASE_ANON_KEY set — the listener then falls
213
+ * back to its own PAIGY_SUPABASE_URL / PAIGY_SUPABASE_ANON_KEY env. */
214
+ realtime: z.object({ url: z.string(), anonKey: z.string() }).nullable()
215
+ });
216
+ var WakeNudgeSchema = z.object({
217
+ kind: z.enum(["reply", "request", "callback"]),
218
+ notificationId: z.string().optional(),
219
+ threadId: z.string()
220
+ });
221
+ var DeviceAgentTokenSchema = z.object({
222
+ token: z.string(),
223
+ deviceId: z.string(),
224
+ agentName: z.string(),
225
+ /** User-chosen session label; defaults to `<agent> <device>`. */
226
+ nickname: z.string(),
227
+ createdAt: z.string().datetime()
228
+ });
229
+ var PairingStatusSchema = z.enum(["pending", "approved", "denied", "expired"]);
230
+ var DeviceCodeSchema = z.object({
231
+ device_code: z.string(),
232
+ user_code: z.string(),
233
+ verification_uri: z.string().url(),
234
+ verification_uri_complete: z.string().url(),
235
+ interval: z.number(),
236
+ expires_in: z.number()
237
+ });
238
+ var DeviceInfoSchema = z.object({
239
+ code: z.string(),
240
+ agent: z.string(),
241
+ device: z.string().nullable(),
242
+ status: PairingStatusSchema
243
+ });
244
+ var DeviceTokenSchema = z.object({
245
+ access_token: z.string(),
246
+ nickname: z.string(),
247
+ agent: z.string(),
248
+ device: z.string().nullable()
249
+ });
250
+
251
+ // src/client.ts
252
+ import { existsSync, readFileSync } from "fs";
253
+ import { homedir } from "os";
254
+ import { join } from "path";
255
+ var BACKEND_URL = process.env.PAIGY_BACKEND_URL ?? "https://paigy.ai";
256
+ var TOKEN_PATH = join(homedir(), ".paigy", "token.json");
257
+ function loadToken() {
258
+ if (process.env.PAIGY_TOKEN) return process.env.PAIGY_TOKEN;
259
+ if (existsSync(TOKEN_PATH)) {
260
+ try {
261
+ const raw = readFileSync(TOKEN_PATH, "utf8");
262
+ const parsed = JSON.parse(raw);
263
+ if (parsed.access_token) return parsed.access_token;
264
+ } catch {
265
+ }
266
+ }
267
+ return "";
268
+ }
269
+ var ONBOARD_MSG = "Not paired with Paigy yet \u2014 call the `pair` tool to connect this agent (it returns an approval link to show the user), then retry. Manual fallback: `npx -y @paigy/mcp paigy-mcp-onboard`.";
270
+ function ensureAuthed(res) {
271
+ if (res.status === 401) throw new Error(ONBOARD_MSG);
272
+ return res;
273
+ }
274
+ async function submitNotification(req) {
275
+ const token = loadToken();
276
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/notify`, {
277
+ method: "POST",
278
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
279
+ body: JSON.stringify(req)
280
+ }));
281
+ if (!res.ok) throw new Error(`notify failed: ${res.status} ${await res.text()}`);
282
+ return await res.json();
283
+ }
284
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
285
+ async function awaitReply(notificationId, opts = {}) {
286
+ const intervalMs = opts.intervalMs ?? 5e3;
287
+ const windowMs = opts.windowMs ?? 3e5;
288
+ const doSleep = opts.sleep ?? sleep;
289
+ const now = opts.now ?? Date.now;
290
+ const token = loadToken();
291
+ const start = now();
292
+ while (true) {
293
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/await?notificationId=${encodeURIComponent(notificationId)}`, {
294
+ headers: { authorization: `Bearer ${token}` }
295
+ }));
296
+ if (!res.ok) throw new Error(`await failed: ${res.status} ${await res.text()}`);
297
+ const item = await res.json();
298
+ if (item.type !== "idle") return item;
299
+ if (now() - start >= windowMs) return { type: "idle" };
300
+ await doSleep(intervalMs);
301
+ }
302
+ }
303
+ async function checkReplies() {
304
+ const token = loadToken();
305
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/pending`, {
306
+ headers: { authorization: `Bearer ${token}` }
307
+ }));
308
+ if (!res.ok) throw new Error(`check_replies failed: ${res.status} ${await res.text()}`);
309
+ return await res.json();
310
+ }
311
+ async function setTaskState(id, state) {
312
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/notify/${id}/state`, {
313
+ method: "PATCH",
314
+ headers: { "content-type": "application/json", authorization: `Bearer ${loadToken()}` },
315
+ body: JSON.stringify({ state })
316
+ }));
317
+ if (!res.ok) throw new Error(`set_task_state failed: ${res.status} ${await res.text()}`);
318
+ return await res.json();
319
+ }
320
+ async function registerDelivery(mode) {
321
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/delivery`, {
322
+ method: "POST",
323
+ headers: { "content-type": "application/json", authorization: `Bearer ${loadToken()}` },
324
+ body: JSON.stringify({ mode })
325
+ }));
326
+ if (!res.ok) throw new Error(`register_delivery failed: ${res.status} ${await res.text()}`);
327
+ return await res.json();
328
+ }
329
+ async function scheduleCallback(req) {
330
+ const token = loadToken();
331
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/callback`, {
332
+ method: "POST",
333
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
334
+ body: JSON.stringify(req)
335
+ }));
336
+ if (!res.ok) throw new Error(`schedule_callback failed: ${res.status} ${await res.text()}`);
337
+ return await res.json();
338
+ }
339
+ async function pollAnswer(id) {
340
+ const token = loadToken();
341
+ const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/poll/${id}`, {
342
+ headers: { authorization: `Bearer ${token}` }
343
+ }));
344
+ if (!res.ok) throw new Error(`poll failed: ${res.status} ${await res.text()}`);
345
+ return await res.json();
346
+ }
347
+
348
+ export {
349
+ NotifyRequestSchema,
350
+ SetTaskStateSchema,
351
+ ScheduleCallbackSchema,
352
+ DeliveryModeSchema,
353
+ WAKE_EVENT,
354
+ wakeChannel,
355
+ submitNotification,
356
+ awaitReply,
357
+ checkReplies,
358
+ setTaskState,
359
+ registerDelivery,
360
+ scheduleCallback,
361
+ pollAnswer
362
+ };
package/dist/index.js CHANGED
@@ -1,4 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ DeliveryModeSchema,
4
+ NotifyRequestSchema,
5
+ ScheduleCallbackSchema,
6
+ SetTaskStateSchema,
7
+ awaitReply,
8
+ checkReplies,
9
+ pollAnswer,
10
+ registerDelivery,
11
+ scheduleCallback,
12
+ setTaskState,
13
+ submitNotification
14
+ } from "./chunk-4MRCUW5I.js";
2
15
  import {
3
16
  deleteToken,
4
17
  openBrowser,
@@ -18,256 +31,27 @@ import {
18
31
  ListToolsRequestSchema
19
32
  } from "@modelcontextprotocol/sdk/types.js";
20
33
  import { execSync } from "child_process";
21
-
22
- // ../../packages/schema/dist/index.js
23
34
  import { z } from "zod";
24
- var ContextSchema = z.object({
25
- title: z.string().min(1).describe("One-line headline of what you need (required, non-empty)."),
26
- description: z.array(z.string().min(1)).min(1).describe("Semantic chunks of detail (each a standalone, non-empty piece). The user can select chunks to ask you to expand.")
27
- });
28
- var OptionSchema = z.object({
29
- id: z.string(),
30
- label: z.string(),
31
- // .describe() flows into the MCP notify_user JSON schema (zodToJsonSchema), so
32
- // the constraints below are what an agent reads when deciding to use these.
33
- html: z.string().max(16384).describe(
34
- "Optional sandboxed HTML/CSS preview for a visual 'pick one' (shown in the option card). Untrusted-sandboxed: NO JavaScript, NO external network or images \u2014 inline CSS and data: URIs only; <=16KB. Use for layout/CSS mockups, tables, diffs. For a hosted image use `image` instead."
35
- ).optional(),
36
- image: z.string().url().describe(
37
- "Optional image URL rendered as the option's preview (plain image, not sandboxed). For agent-generated HTML/CSS mockups, use `html` instead."
38
- ).optional()
39
- });
40
- var VisualSchema = z.object({
41
- url: z.string().url(),
42
- label: z.string().optional()
43
- });
44
- var AgentSchema = z.object({
45
- name: z.string()
46
- });
47
- var NotifyRequestSchema = z.object({
48
- context: ContextSchema,
49
- options: z.array(OptionSchema).optional(),
50
- visuals: z.array(VisualSchema).optional(),
51
- agent: AgentSchema,
52
- /** Git repo the agent is working in ("owner/name"), when applicable. */
53
- repo: z.string().optional(),
54
- /** Git branch the agent is on, when applicable. */
55
- branch: z.string().optional(),
56
- /** Continue an existing conversation; omitted = start a new thread. */
57
- threadId: z.string().uuid().optional(),
58
- createdAt: z.string().datetime(),
59
- urgency: z.enum(["inbox", "call"]).default("inbox").describe(
60
- "'inbox' (default) = sits silently in the inbox for the user to get to. 'call' = rings the user's phone now (a CallKit voice call) \u2014 use only when you genuinely need them in the moment (blocked and waiting, time-sensitive). context.title becomes what they see on the ring, so make it specific."
61
- ),
62
- /** The request this one was spawned from, for a clarification. */
63
- parentId: z.string().optional(),
64
- /** How the user answers the options: pick one (default), pick several, or pick & order. */
65
- select: z.enum(["one", "many", "rank"]).default("one")
66
- });
67
- var NotifyStatusSchema = z.enum(["pending", "answered", "ignored"]);
68
- var AgentStateSchema = z.enum(["idle", "in_progress", "completed", "needs_input"]);
69
- var SetTaskStateSchema = z.object({
70
- state: z.enum(["in_progress", "completed", "needs_input"])
71
- });
72
- var UserAnswerSchema = z.discriminatedUnion("kind", [
73
- z.object({ kind: z.literal("option"), optionId: z.string() }),
74
- z.object({ kind: z.literal("text"), text: z.string() }),
75
- z.object({ kind: z.literal("ignored") }),
76
- z.object({ kind: z.literal("multi"), optionIds: z.array(z.string()) }),
77
- z.object({ kind: z.literal("ranked"), optionIds: z.array(z.string()) }),
78
- z.object({ kind: z.literal("clarify"), chunks: z.array(z.string()).min(1) })
79
- ]);
80
- var AwaitItemSchema = z.discriminatedUnion("type", [
81
- z.object({
82
- type: z.literal("reply"),
83
- threadId: z.string(),
84
- notificationId: z.string(),
85
- answer: UserAnswerSchema
86
- }),
87
- z.object({
88
- type: z.literal("remind"),
89
- threadId: z.string(),
90
- notificationId: z.string(),
91
- remindAt: z.string().datetime({ offset: true }),
92
- /** Seconds until remindAt, server-computed — pass straight to ScheduleWakeup. */
93
- remindInSeconds: z.number()
94
- }),
95
- z.object({ type: z.literal("idle") })
96
- ]);
97
- var PendingRepliesSchema = z.object({
98
- replies: z.array(
99
- z.object({ threadId: z.string(), notificationId: z.string(), answer: UserAnswerSchema })
100
- ),
101
- pending: z.array(
102
- z.object({ threadId: z.string(), notificationId: z.string(), createdAt: z.string() })
103
- )
104
- });
105
- var NotifyResponseSchema = z.object({
106
- id: z.string(),
107
- status: NotifyStatusSchema,
108
- createdAt: z.string().datetime(),
109
- answer: UserAnswerSchema.optional(),
110
- answeredAt: z.string().datetime().optional()
111
- });
112
- var UserResponseSchema = z.object({
113
- requestId: z.string(),
114
- answer: UserAnswerSchema,
115
- answeredAt: z.string().datetime()
116
- });
117
- var InboxItemSchema = z.object({
118
- id: z.string(),
119
- status: NotifyStatusSchema,
120
- context: ContextSchema,
121
- options: z.array(OptionSchema).optional(),
122
- visuals: z.array(VisualSchema).optional(),
123
- agent: z.string(),
124
- nickname: z.string(),
125
- repo: z.string().optional(),
126
- branch: z.string().optional(),
127
- createdAt: z.string().datetime(),
128
- snoozedUntil: z.string().datetime().optional(),
129
- agentState: AgentStateSchema.default("idle"),
130
- parentId: z.string().optional(),
131
- select: z.enum(["one", "many", "rank"]).default("one")
132
- });
133
- var SnoozeRequestSchema = z.object({
134
- requestId: z.string(),
135
- until: z.string().datetime()
136
- });
137
- var PushTokenSchema = z.object({
138
- voipToken: z.string().min(1),
139
- platform: z.enum(["ios"])
140
- });
141
- var UserSettingsSchema = z.object({
142
- callsEnabled: z.boolean()
143
- });
144
- var DeviceAgentTokenSchema = z.object({
145
- token: z.string(),
146
- deviceId: z.string(),
147
- agentName: z.string(),
148
- /** User-chosen session label; defaults to `<agent> <device>`. */
149
- nickname: z.string(),
150
- createdAt: z.string().datetime()
151
- });
152
- var PairingStatusSchema = z.enum(["pending", "approved", "denied", "expired"]);
153
- var DeviceCodeSchema = z.object({
154
- device_code: z.string(),
155
- user_code: z.string(),
156
- verification_uri: z.string().url(),
157
- verification_uri_complete: z.string().url(),
158
- interval: z.number(),
159
- expires_in: z.number()
160
- });
161
- var DeviceInfoSchema = z.object({
162
- code: z.string(),
163
- agent: z.string(),
164
- device: z.string().nullable(),
165
- status: PairingStatusSchema
166
- });
167
- var DeviceTokenSchema = z.object({
168
- access_token: z.string(),
169
- nickname: z.string(),
170
- agent: z.string(),
171
- device: z.string().nullable()
172
- });
173
-
174
- // src/index.ts
175
- import { z as z2 } from "zod";
176
35
  import { zodToJsonSchema } from "zod-to-json-schema";
177
-
178
- // src/client.ts
179
- import { existsSync, readFileSync } from "fs";
180
- import { homedir } from "os";
181
- import { join } from "path";
182
- var BACKEND_URL = process.env.PAIGY_BACKEND_URL ?? "https://paigy.ai";
183
- var TOKEN_PATH = join(homedir(), ".paigy", "token.json");
184
- function loadToken() {
185
- if (process.env.PAIGY_TOKEN) return process.env.PAIGY_TOKEN;
186
- if (existsSync(TOKEN_PATH)) {
187
- try {
188
- const raw = readFileSync(TOKEN_PATH, "utf8");
189
- const parsed = JSON.parse(raw);
190
- if (parsed.access_token) return parsed.access_token;
191
- } catch {
192
- }
193
- }
194
- return "";
195
- }
196
- var ONBOARD_MSG = "Not paired with Paigy yet \u2014 call the `pair` tool to connect this agent (it returns an approval link to show the user), then retry. Manual fallback: `npx -y @paigy/mcp paigy-mcp-onboard`.";
197
- function ensureAuthed(res) {
198
- if (res.status === 401) throw new Error(ONBOARD_MSG);
199
- return res;
200
- }
201
- async function submitNotification(req) {
202
- const token = loadToken();
203
- const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/notify`, {
204
- method: "POST",
205
- headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
206
- body: JSON.stringify(req)
207
- }));
208
- if (!res.ok) throw new Error(`notify failed: ${res.status} ${await res.text()}`);
209
- return await res.json();
210
- }
211
- var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
212
- async function awaitReply(notificationId, opts = {}) {
213
- const intervalMs = opts.intervalMs ?? 5e3;
214
- const windowMs = opts.windowMs ?? 3e5;
215
- const doSleep = opts.sleep ?? sleep2;
216
- const now = opts.now ?? Date.now;
217
- const token = loadToken();
218
- const start = now();
219
- while (true) {
220
- const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/await?notificationId=${encodeURIComponent(notificationId)}`, {
221
- headers: { authorization: `Bearer ${token}` }
222
- }));
223
- if (!res.ok) throw new Error(`await failed: ${res.status} ${await res.text()}`);
224
- const item = await res.json();
225
- if (item.type !== "idle") return item;
226
- if (now() - start >= windowMs) return { type: "idle" };
227
- await doSleep(intervalMs);
228
- }
229
- }
230
- async function checkReplies() {
231
- const token = loadToken();
232
- const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/pending`, {
233
- headers: { authorization: `Bearer ${token}` }
234
- }));
235
- if (!res.ok) throw new Error(`check_replies failed: ${res.status} ${await res.text()}`);
236
- return await res.json();
237
- }
238
- async function setTaskState(id, state) {
239
- const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/notify/${id}/state`, {
240
- method: "PATCH",
241
- headers: { "content-type": "application/json", authorization: `Bearer ${loadToken()}` },
242
- body: JSON.stringify({ state })
243
- }));
244
- if (!res.ok) throw new Error(`set_task_state failed: ${res.status} ${await res.text()}`);
245
- return await res.json();
246
- }
247
- async function pollAnswer(id) {
248
- const token = loadToken();
249
- const res = ensureAuthed(await fetch(`${BACKEND_URL}/api/poll/${id}`, {
250
- headers: { authorization: `Bearer ${token}` }
251
- }));
252
- if (!res.ok) throw new Error(`poll failed: ${res.status} ${await res.text()}`);
253
- return await res.json();
254
- }
255
-
256
- // src/index.ts
257
- var PollAnswerSchema = z2.object({
258
- id: z2.string().describe("Request id returned by notify_user.")
36
+ var PollAnswerSchema = z.object({
37
+ id: z.string().describe("Request id returned by notify_user.")
259
38
  });
260
- var AwaitReplySchema = z2.object({
261
- notificationId: z2.string().describe("The id returned by notify_user \u2014 waits for the user's reply to THIS notification only.")
39
+ var AwaitReplySchema = z.object({
40
+ notificationId: z.string().describe("The id returned by notify_user \u2014 waits for the user's reply to THIS notification only.")
262
41
  });
263
- var CheckRepliesSchema = z2.object({});
264
- var PairSchema = z2.object({
265
- device_code: z2.string().optional().describe("Omit to start pairing (returns an approval link to show the user). Pass the device_code from that first call to finish, once the user has approved.")
42
+ var CheckRepliesSchema = z.object({});
43
+ var PairSchema = z.object({
44
+ device_code: z.string().optional().describe("Omit to start pairing (returns an approval link to show the user). Pass the device_code from that first call to finish, once the user has approved.")
266
45
  });
267
- var SetTaskStateToolSchema = z2.object({
268
- notificationId: z2.string(),
46
+ var SetTaskStateToolSchema = z.object({
47
+ notificationId: z.string(),
269
48
  state: SetTaskStateSchema.shape.state
270
49
  });
50
+ var RegisterDeliveryToolSchema = z.object({
51
+ mode: DeliveryModeSchema.describe(
52
+ "'self_hosted' = the API pushes the moment work lands (requires `npx -y @paigy/mcp paigy-listen` running); 'poll' = the default, you catch up via check_replies/await_reply."
53
+ )
54
+ });
271
55
  function detectGit() {
272
56
  const run = (cmd) => {
273
57
  try {
@@ -288,7 +72,7 @@ var server = new Server(
288
72
  { name: "paigy", version: "0.0.0" },
289
73
  {
290
74
  capabilities: { tools: {} },
291
- instructions: "On startup, call check_replies once to pick up any replies or pending work you missed while away. To wait for the answer to something you just asked, call await_reply with that notification's id \u2014 it's scoped to that one request, so it never returns replies meant for other requests. Use check_replies again only when re-booting or after waiting a long time on something else. Never end a turn that still needs the user without notify_user + await_reply. If a reply comes back as { kind: 'clarify', chunks: [...] }, the user wants more detail on those chunks \u2014 respond by calling notify_user again with the SAME threadId and an expanded description covering them."
75
+ instructions: "On startup, call check_replies once to pick up any replies or pending work you missed while away. To wait for the answer to something you just asked, call await_reply with that notification's id \u2014 it's scoped to that one request, so it never returns replies meant for other requests. Use check_replies again only when re-booting or after waiting a long time on something else. Never end a turn that still needs the user without notify_user + await_reply. When you need a decision or input, PREFER a structured answer (select:'confirm', 'one', 'many', or 'rank') over an open-ended free-text ask \u2014 structured options save the user a tap, and they can always add free text on top. If a reply comes back as { kind: 'clarify', chunks: [...] }, the user wants more detail on those chunks \u2014 respond by calling notify_user again with the SAME threadId and an expanded description covering them. When urgency is 'call', remember the title + description are spoken aloud \u2014 write them short and conversational, and name things instead of using IDs (e.g. 'the pull request about the agents page', not 'PR #235'). When the user asks you to follow up later \u2014 when you're done, if you're blocked, or at a set time \u2014 record it with schedule_callback so you don't drop it if you go idle."
292
76
  }
293
77
  );
294
78
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
@@ -301,11 +85,11 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
301
85
  {
302
86
  name: "unpair",
303
87
  description: "Log out / unpair this agent from the user's Paigy account: revokes the token server-side (it stops working everywhere) and deletes the local ~/.paigy/token.json. Takes no arguments. After this, notify_user/await_reply won't work until the user pairs again with the pair tool.",
304
- inputSchema: zodToJsonSchema(z2.object({}), { target: "openApi3" })
88
+ inputSchema: zodToJsonSchema(z.object({}), { target: "openApi3" })
305
89
  },
306
90
  {
307
91
  name: "notify_user",
308
- description: "Notify the user via Paigy and get a request id to poll for their answer. Provide context.title (a specific, non-empty one-line headline \u2014 this is what the user sees first, and what shows on the ring for a call) and context.description (an array of standalone, non-empty detail chunks the user can selectively ask you to expand). Set `urgency`: 'inbox' (default) drops it silently in their inbox; 'call' rings their phone now as a voice call \u2014 use 'call' only when you genuinely need them in the moment (blocked/waiting, time-sensitive), not for routine FYIs. Plus optional options (answerable choices; each may carry a sandboxed `html` or an `image` preview for a visual 'pick one' \u2014 e.g. show layout/UI alternatives) and visuals. Use `select` to control how the user answers options: 'one' (default) = pick a single option; 'many' = multi-select, user checks any subset \u2192 answer arrives as {kind:'multi', optionIds:[...]}; 'rank' = select and order, user taps options in preferred order \u2192 answer arrives as {kind:'ranked', optionIds:[...]} (ordered by choice). If a reply comes back as {kind:'clarify', chunks:[...]}, the user wants more detail on those chunks \u2014 respond via notify_user with the SAME threadId and an expanded description. Pass `threadId` from a prior notify_user result or an await_reply reply to continue that conversation thread; omit it to start a new one.",
92
+ description: "Notify the user via Paigy and get a request id to poll for their answer. Provide context.title (a specific, non-empty one-line headline \u2014 this is what the user sees first, and what shows on the ring for a call) and context.description (an array of standalone, non-empty detail chunks the user can selectively ask you to expand). Set `urgency`: 'inbox' (default) drops it silently in their inbox; 'push' is a quiet passive notification (no sound); 'banner' sends a time-sensitive banner/lock-screen push (a 'paige') they tap to open \u2014 for when you need them soon-ish but not enough to ring them; 'call' rings their phone now as a voice call \u2014 only when you genuinely need them in the moment (blocked/waiting, time-sensitive). ON A CALL, your title + description are READ ALOUD by a voice \u2014 write them to be HEARD, not read: keep it short and conversational, front-load the ask, and refer to things BY NAME, not by ID or code (say 'the pull request about the agents page', not 'PR #235'; 'the login-bug ticket', not 'ABC-1234'). Spell out only what's natural to say out loud. DEFAULT to a structured answer shape \u2014 structured options save the user a tap, and they can ALWAYS add free text on top of any structured paige, so you lose nothing by structuring it. Pick the answer shape with `select` \u2014 DON'T leave a decision as open-ended free text: a yes/no or approve/deny \u2192 select:'confirm' (set confirmStyle:'approve' for Approve/Deny); it's answerable right from the banner and arrives as {kind:'confirm', approved:boolean}. Pick one of several \u2192 options + select:'one' (default) \u2192 {kind:'option', optionId}. Pick several \u2192 select:'many' \u2192 {kind:'multi', optionIds:[...]}. Rank/order a subset \u2192 select:'rank', user taps in preferred order \u2192 {kind:'ranked', optionIds:[...]}. For visual choices give each option a sandboxed `html` or an `image` preview (e.g. layout/UI alternatives). Only leave options off (pure free text / voice) when the answer genuinely can't be structured. Plus optional visuals. If a reply comes back as {kind:'clarify', chunks:[...]}, the user wants more detail on those chunks \u2014 respond via notify_user with the SAME threadId and an expanded description. Pass `threadId` from a prior notify_user result or an await_reply reply to continue that conversation thread; omit it to start a new one. To follow up on a call (e.g. the user asked you to 'call me back when it's done'), reuse the threadId from that call's reply so it threads as the same conversation.",
309
93
  inputSchema: zodToJsonSchema(NotifyRequestSchema, { target: "openApi3" })
310
94
  },
311
95
  {
@@ -315,18 +99,28 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
315
99
  },
316
100
  {
317
101
  name: "await_reply",
318
- description: "Wait for the user's reply to THE specific notification you sent for the current request (pass its id from notify_user). This is how you wait for your answer in-context. Polls ~5 min; returns { type:'reply', answer } when they respond, { type:'remind', remindInSeconds } on snooze (ScheduleWakeup then await_reply again), or { type:'idle' }. Scoped to that one notification \u2014 it NEVER returns replies meant for other notifications/requests, so concurrent requests don't cross.",
102
+ description: "Wait for the user's reply to THE specific notification you sent for the current request (pass its id from notify_user). This is how you wait for your answer in-context. Polls ~5 min; returns { type:'reply', answer } when they respond, { type:'remind', remindInSeconds } on snooze (ScheduleWakeup then await_reply again), or { type:'idle' }. Scoped to that one notification \u2014 it NEVER returns replies meant for other notifications/requests, so concurrent requests don't cross. A CALL answer can come back as {kind:'turns', turns:[{prompt,reply}]} \u2014 the ordered log of that call. Read turns[0].reply as the user's main instruction and any later turns as their follow-up (e.g. the end-of-call 'call me back when it's done / I have a blocking question' reply). If they asked for a callback, re-engage in the SAME thread (notify_user with the reply's threadId) when the task is done or you hit a blocker \u2014 urgency:'call' for a blocker, 'banner'/'push'/'inbox' for done. Paigy has no scheduler; the callback is yours to send (use ScheduleWakeup/cron for timing).",
319
103
  inputSchema: zodToJsonSchema(AwaitReplySchema, { target: "openApi3" })
320
104
  },
321
105
  {
322
106
  name: "check_replies",
323
- description: "The catch-up router for everything NOT tied to your current request: returns replies the user sent that you haven't seen yet (now marked seen) plus still-pending notifications you sent. Use it when booting up / starting a session, or when you've been waiting a long time on something else, to discover acks or work you're unaware of. To wait on a request you just sent, use await_reply instead.",
107
+ description: "The catch-up router for everything NOT tied to your current request: returns replies the user sent that you haven't seen yet (now marked seen), still-pending notifications you sent, and `requests` \u2014 new requests the user started toward you (each { notificationId, threadId, text }, returned once). Act on each request and reply with notify_user on the SAME threadId. Use it when booting up / starting a session, or when you've been waiting a long time on something else, to discover acks or work you're unaware of. To wait on a request you just sent, use await_reply instead. Also returns owedCallbacks: callbacks now due that you promised \u2014 fulfill each with notify_user on its threadId.",
324
108
  inputSchema: zodToJsonSchema(CheckRepliesSchema, { target: "openApi3" })
325
109
  },
326
110
  {
327
111
  name: "set_task_state",
328
112
  description: "Report progress on a request you received: in_progress (you started working), completed (done), or needs_input (you need more from the user \u2014 usually paired with a notify_user carrying parentId = this request's id).",
329
113
  inputSchema: zodToJsonSchema(SetTaskStateToolSchema, { target: "openApi3" })
114
+ },
115
+ {
116
+ name: "register_delivery",
117
+ description: "Choose how Paigy reaches you when a reply or new request lands. 'self_hosted' makes Paigy PUSH it instantly over a realtime channel instead of you polling \u2014 but it only helps if a `paigy listen` daemon is running (npx -y @paigy/mcp paigy-listen), which the user runs once. 'poll' (default) keeps the catch-up model (check_replies / await_reply). Either way no work is ever lost: a missed push is reconciled by your next check_replies sweep.",
118
+ inputSchema: zodToJsonSchema(RegisterDeliveryToolSchema, { target: "openApi3" })
119
+ },
120
+ {
121
+ name: "schedule_callback",
122
+ description: "Promise the user a follow-up you'll keep even if you go idle. Use it when they ask you to report back: trigger 'on_done' (when you finish \u2014 fires when you call set_task_state completed), 'on_blocked' (if you hit a blocker \u2014 fires on set_task_state needs_input), or 'scheduled' with dueInSeconds (e.g. 'remind me in 10 min'). Pass the threadId of the conversation and a short note. Fulfill it by calling notify_user on that threadId; check_replies re-lists due callbacks until you do.",
123
+ inputSchema: zodToJsonSchema(ScheduleCallbackSchema, { target: "openApi3" })
330
124
  }
331
125
  ]
332
126
  }));
@@ -431,6 +225,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
431
225
  const result = await setTaskState(notificationId, state);
432
226
  return { content: [{ type: "text", text: JSON.stringify(result) }] };
433
227
  }
228
+ case "register_delivery": {
229
+ const { mode } = RegisterDeliveryToolSchema.parse(request.params.arguments);
230
+ const result = await registerDelivery(mode);
231
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
232
+ }
233
+ case "schedule_callback": {
234
+ const result = await scheduleCallback(ScheduleCallbackSchema.parse(request.params.arguments));
235
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
236
+ }
434
237
  default:
435
238
  throw new Error(`Unknown tool: ${request.params.name}`);
436
239
  }
package/dist/listen.js ADDED
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ WAKE_EVENT,
4
+ checkReplies,
5
+ registerDelivery,
6
+ wakeChannel
7
+ } from "./chunk-4MRCUW5I.js";
8
+
9
+ // src/listen.ts
10
+ import { createClient } from "@supabase/supabase-js";
11
+ import { spawn } from "child_process";
12
+ var emit = (obj) => void process.stdout.write(JSON.stringify(obj) + "\n");
13
+ async function sweep(reason) {
14
+ try {
15
+ const work = await checkReplies();
16
+ emit({ type: "sweep", reason, ...work });
17
+ const cmd = process.env.PAIGY_ON_WAKE;
18
+ if (cmd && (work.replies.length > 0 || work.requests.length > 0 || work.owedCallbacks.length > 0)) {
19
+ spawn(cmd, { shell: true, stdio: "inherit" });
20
+ }
21
+ } catch (e) {
22
+ emit({ type: "error", reason, message: e.message });
23
+ }
24
+ }
25
+ async function main() {
26
+ const cfg = await registerDelivery("self_hosted");
27
+ const url = cfg.realtime?.url ?? process.env.PAIGY_SUPABASE_URL;
28
+ const anonKey = cfg.realtime?.anonKey ?? process.env.PAIGY_SUPABASE_ANON_KEY;
29
+ if (!url || !anonKey) {
30
+ throw new Error(
31
+ "No Realtime credentials \u2014 set SUPABASE_ANON_KEY on the server, or PAIGY_SUPABASE_URL + PAIGY_SUPABASE_ANON_KEY locally."
32
+ );
33
+ }
34
+ const channel = wakeChannel(cfg.tokenId);
35
+ emit({ type: "listening", channel });
36
+ await sweep("boot");
37
+ const sb = createClient(url, anonKey, { auth: { persistSession: false } });
38
+ sb.channel(channel).on(
39
+ "broadcast",
40
+ { event: WAKE_EVENT },
41
+ (msg) => void sweep(`wake:${msg.payload?.kind ?? "?"}`)
42
+ ).subscribe();
43
+ const shutdown = async () => {
44
+ try {
45
+ await registerDelivery("poll");
46
+ } catch {
47
+ }
48
+ process.exit(0);
49
+ };
50
+ process.on("SIGINT", () => void shutdown());
51
+ process.on("SIGTERM", () => void shutdown());
52
+ }
53
+ if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/^file:\/\//, ""))) {
54
+ main().catch((e) => {
55
+ emit({ type: "fatal", message: e.message });
56
+ process.exit(1);
57
+ });
58
+ }
59
+ export {
60
+ sweep
61
+ };
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@paigy/mcp",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Paigy MCP server — a voice inbox for your AI agents. Lets an agent notify a user and await their reply.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "mcp": "./dist/index.js",
9
9
  "paigy-mcp": "./dist/index.js",
10
- "paigy-mcp-onboard": "./dist/onboard.js"
10
+ "paigy-mcp-onboard": "./dist/onboard.js",
11
+ "paigy-listen": "./dist/listen.js"
11
12
  },
12
13
  "files": [
13
14
  "dist"
@@ -21,14 +22,15 @@
21
22
  "directory": "apps/mcp"
22
23
  },
23
24
  "scripts": {
24
- "build": "tsup src/index.ts src/onboard.ts --format esm --clean",
25
- "dev": "tsup src/index.ts src/onboard.ts --format esm --watch",
25
+ "build": "tsup src/index.ts src/onboard.ts src/listen.ts --format esm --clean",
26
+ "dev": "tsup src/index.ts src/onboard.ts src/listen.ts --format esm --watch",
26
27
  "typecheck": "tsc --noEmit",
27
28
  "test": "vitest run",
28
29
  "prepublishOnly": "pnpm --filter @paigy/schema build && pnpm build"
29
30
  },
30
31
  "dependencies": {
31
32
  "@modelcontextprotocol/sdk": "^1.0.4",
33
+ "@supabase/supabase-js": "^2.47.10",
32
34
  "zod": "^3.24.1",
33
35
  "zod-to-json-schema": "^3.24.1"
34
36
  },
@@ -39,4 +41,4 @@
39
41
  "typescript": "^5.7.2",
40
42
  "vitest": "^2.1.8"
41
43
  }
42
- }
44
+ }