@pergy-ai/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mauricio Urdaneta Uribe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # @pergy-ai/mcp
2
+
3
+ A voice inbox for your AI agents. This MCP server lets an agent **notify a user** and **await their reply** — so a long-running agent can ask a question, hand off, and resume on the answer.
4
+
5
+ ## Install
6
+
7
+ No clone needed — run it with `npx`:
8
+
9
+ ```bash
10
+ npx @pergy-ai/mcp
11
+ ```
12
+
13
+ Or wire it into an MCP client config:
14
+
15
+ ```json
16
+ {
17
+ "mcpServers": {
18
+ "pergy": {
19
+ "command": "npx",
20
+ "args": ["-y", "@pergy-ai/mcp"],
21
+ "env": { "PERGY_BACKEND_URL": "https://pergy.ai" }
22
+ }
23
+ }
24
+ }
25
+ ```
26
+
27
+ First-time pairing (link the server to your Pergy account):
28
+
29
+ ```bash
30
+ npx -p @pergy-ai/mcp pergy-mcp-onboard
31
+ ```
32
+
33
+ ## Tools
34
+
35
+ - **`notify_user`** — notify the user (three standalone context tiers: short / medium / long, plus optional options, visuals, `urgency`, and `parentId` for a clarification). Returns a request id + thread id.
36
+ - **`await_task`** — wait for the user's next reply (`reply` / `remind` / `idle`).
37
+ - **`poll_answer`** — fetch the answer to a specific request by id.
38
+ - **`set_task_state`** — report progress on a request: `in_progress` / `completed` / `needs_input`.
39
+
40
+ ## Configuration
41
+
42
+ - `PERGY_BACKEND_URL` — the Pergy API base (defaults to the hosted backend).
43
+
44
+ ## License
45
+
46
+ MIT
package/dist/index.js ADDED
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import {
7
+ CallToolRequestSchema,
8
+ ListToolsRequestSchema
9
+ } from "@modelcontextprotocol/sdk/types.js";
10
+ import { execSync } from "child_process";
11
+
12
+ // ../../packages/schema/dist/index.js
13
+ import { z } from "zod";
14
+ var ContextTiersSchema = z.object({
15
+ short: z.string().describe("The minimum words needed to communicate the message \u2014 a headline."),
16
+ medium: z.string().describe("A standalone ~3 sentence version."),
17
+ long: z.string().describe("A standalone version of 1-3 paragraphs.")
18
+ });
19
+ var OptionSchema = z.object({
20
+ id: z.string(),
21
+ label: z.string()
22
+ });
23
+ var VisualSchema = z.object({
24
+ url: z.string().url(),
25
+ label: z.string().optional()
26
+ });
27
+ var AgentSchema = z.object({
28
+ name: z.string()
29
+ });
30
+ var NotifyRequestSchema = z.object({
31
+ context: ContextTiersSchema,
32
+ options: z.array(OptionSchema).optional(),
33
+ visuals: z.array(VisualSchema).optional(),
34
+ agent: AgentSchema,
35
+ /** Git repo the agent is working in ("owner/name"), when applicable. */
36
+ repo: z.string().optional(),
37
+ /** Git branch the agent is on, when applicable. */
38
+ branch: z.string().optional(),
39
+ /** Continue an existing conversation; omitted = start a new thread. */
40
+ threadId: z.string().uuid().optional(),
41
+ createdAt: z.string().datetime(),
42
+ /** Whether this should ring the user (SP3) or sit in the inbox. Inert until SP3. */
43
+ urgency: z.enum(["inbox", "call"]).default("inbox"),
44
+ /** The request this one was spawned from, for a clarification. */
45
+ parentId: z.string().optional()
46
+ });
47
+ var NotifyStatusSchema = z.enum(["pending", "answered", "ignored"]);
48
+ var AgentStateSchema = z.enum(["idle", "in_progress", "completed", "needs_input"]);
49
+ var SetTaskStateSchema = z.object({
50
+ state: z.enum(["in_progress", "completed", "needs_input"])
51
+ });
52
+ var UserAnswerSchema = z.discriminatedUnion("kind", [
53
+ z.object({ kind: z.literal("option"), optionId: z.string() }),
54
+ z.object({ kind: z.literal("text"), text: z.string() }),
55
+ z.object({ kind: z.literal("ignored") })
56
+ ]);
57
+ var AwaitItemSchema = z.discriminatedUnion("type", [
58
+ z.object({
59
+ type: z.literal("reply"),
60
+ threadId: z.string(),
61
+ notificationId: z.string(),
62
+ answer: UserAnswerSchema
63
+ }),
64
+ z.object({
65
+ type: z.literal("remind"),
66
+ threadId: z.string(),
67
+ notificationId: z.string(),
68
+ remindAt: z.string().datetime({ offset: true }),
69
+ /** Seconds until remindAt, server-computed — pass straight to ScheduleWakeup. */
70
+ remindInSeconds: z.number()
71
+ }),
72
+ z.object({ type: z.literal("idle") })
73
+ ]);
74
+ var NotifyResponseSchema = z.object({
75
+ id: z.string(),
76
+ status: NotifyStatusSchema,
77
+ createdAt: z.string().datetime(),
78
+ answer: UserAnswerSchema.optional(),
79
+ answeredAt: z.string().datetime().optional()
80
+ });
81
+ var UserResponseSchema = z.object({
82
+ requestId: z.string(),
83
+ answer: UserAnswerSchema,
84
+ answeredAt: z.string().datetime()
85
+ });
86
+ var InboxItemSchema = z.object({
87
+ id: z.string(),
88
+ context: ContextTiersSchema,
89
+ options: z.array(OptionSchema).optional(),
90
+ visuals: z.array(VisualSchema).optional(),
91
+ agent: z.string(),
92
+ nickname: z.string(),
93
+ repo: z.string().optional(),
94
+ branch: z.string().optional(),
95
+ createdAt: z.string().datetime(),
96
+ snoozedUntil: z.string().datetime().optional(),
97
+ agentState: AgentStateSchema.default("idle"),
98
+ parentId: z.string().optional()
99
+ });
100
+ var SnoozeRequestSchema = z.object({
101
+ requestId: z.string(),
102
+ until: z.string().datetime()
103
+ });
104
+ var DeviceAgentTokenSchema = z.object({
105
+ token: z.string(),
106
+ deviceId: z.string(),
107
+ agentName: z.string(),
108
+ /** User-chosen session label; defaults to `<agent> <device>`. */
109
+ nickname: z.string(),
110
+ createdAt: z.string().datetime()
111
+ });
112
+ var PairingStatusSchema = z.enum(["pending", "approved", "denied", "expired"]);
113
+ var DeviceCodeSchema = z.object({
114
+ device_code: z.string(),
115
+ user_code: z.string(),
116
+ verification_uri: z.string().url(),
117
+ verification_uri_complete: z.string().url(),
118
+ interval: z.number(),
119
+ expires_in: z.number()
120
+ });
121
+ var DeviceInfoSchema = z.object({
122
+ code: z.string(),
123
+ agent: z.string(),
124
+ device: z.string().nullable(),
125
+ status: PairingStatusSchema
126
+ });
127
+ var DeviceTokenSchema = z.object({
128
+ access_token: z.string(),
129
+ nickname: z.string(),
130
+ agent: z.string(),
131
+ device: z.string().nullable()
132
+ });
133
+
134
+ // src/index.ts
135
+ import { z as z2 } from "zod";
136
+ import { zodToJsonSchema } from "zod-to-json-schema";
137
+
138
+ // src/client.ts
139
+ import { existsSync, readFileSync } from "fs";
140
+ import { homedir } from "os";
141
+ import { join } from "path";
142
+ var BACKEND_URL = process.env.PERGY_BACKEND_URL ?? "http://localhost:3000";
143
+ var TOKEN_PATH = join(homedir(), ".pergy", "token.json");
144
+ function loadToken() {
145
+ if (process.env.PERGY_TOKEN) return process.env.PERGY_TOKEN;
146
+ if (existsSync(TOKEN_PATH)) {
147
+ try {
148
+ const raw = readFileSync(TOKEN_PATH, "utf8");
149
+ const parsed = JSON.parse(raw);
150
+ if (parsed.access_token) return parsed.access_token;
151
+ } catch {
152
+ }
153
+ }
154
+ return "";
155
+ }
156
+ async function submitNotification(req) {
157
+ const token = loadToken();
158
+ const res = await fetch(`${BACKEND_URL}/api/notify`, {
159
+ method: "POST",
160
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
161
+ body: JSON.stringify(req)
162
+ });
163
+ if (!res.ok) throw new Error(`notify failed: ${res.status} ${await res.text()}`);
164
+ return await res.json();
165
+ }
166
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
167
+ async function awaitTask(opts = {}) {
168
+ const intervalMs = opts.intervalMs ?? 5e3;
169
+ const windowMs = opts.windowMs ?? 3e5;
170
+ const doSleep = opts.sleep ?? sleep;
171
+ const now = opts.now ?? Date.now;
172
+ const token = loadToken();
173
+ const start = now();
174
+ while (true) {
175
+ const res = await fetch(`${BACKEND_URL}/api/await`, {
176
+ headers: { authorization: `Bearer ${token}` }
177
+ });
178
+ if (!res.ok) throw new Error(`await failed: ${res.status} ${await res.text()}`);
179
+ const item = await res.json();
180
+ if (item.type !== "idle") return item;
181
+ if (now() - start >= windowMs) return { type: "idle" };
182
+ await doSleep(intervalMs);
183
+ }
184
+ }
185
+ async function setTaskState(id, state) {
186
+ const res = await fetch(`${BACKEND_URL}/api/notify/${id}/state`, {
187
+ method: "PATCH",
188
+ headers: { "content-type": "application/json", authorization: `Bearer ${loadToken()}` },
189
+ body: JSON.stringify({ state })
190
+ });
191
+ if (!res.ok) throw new Error(`set_task_state failed: ${res.status} ${await res.text()}`);
192
+ return await res.json();
193
+ }
194
+ async function pollAnswer(id) {
195
+ const token = loadToken();
196
+ const res = await fetch(`${BACKEND_URL}/api/poll/${id}`, {
197
+ headers: { authorization: `Bearer ${token}` }
198
+ });
199
+ if (!res.ok) throw new Error(`poll failed: ${res.status} ${await res.text()}`);
200
+ return await res.json();
201
+ }
202
+
203
+ // src/index.ts
204
+ var PollAnswerSchema = z2.object({
205
+ id: z2.string().describe("Request id returned by notify_user.")
206
+ });
207
+ var AwaitTaskSchema = z2.object({});
208
+ var SetTaskStateToolSchema = z2.object({
209
+ notificationId: z2.string(),
210
+ state: SetTaskStateSchema.shape.state
211
+ });
212
+ function detectGit() {
213
+ const run = (cmd) => {
214
+ try {
215
+ return execSync(cmd, { stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" }).trim();
216
+ } catch {
217
+ return "";
218
+ }
219
+ };
220
+ const remote = run("git remote get-url origin");
221
+ const match = remote.match(/[:/]([^/:]+\/[^/]+?)(?:\.git)?$/);
222
+ const branch = run("git rev-parse --abbrev-ref HEAD");
223
+ return {
224
+ repo: match ? match[1] : void 0,
225
+ branch: branch && branch !== "HEAD" ? branch : void 0
226
+ };
227
+ }
228
+ var server = new Server(
229
+ { name: "pergy", version: "0.0.0" },
230
+ { capabilities: { tools: {} } }
231
+ );
232
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
233
+ tools: [
234
+ {
235
+ name: "notify_user",
236
+ description: "Notify the user via Pergy and get a request id to poll for their answer. Provide context in three STANDALONE tiers (each must communicate on its own, not as a delta): short = minimum words, a headline; medium = ~3 sentences; long = 1-3 paragraphs. Plus optional options and visuals. Pass `threadId` from a prior notify_user result or an await_task reply to continue that conversation thread; omit it to start a new one.",
237
+ inputSchema: zodToJsonSchema(NotifyRequestSchema, { target: "openApi3" })
238
+ },
239
+ {
240
+ name: "poll_answer",
241
+ description: "Fetch the user's answer to a previous notify_user request. Returns status pending | answered | ignored, with the answer once present. Errors if the id is unknown or expired.",
242
+ inputSchema: zodToJsonSchema(PollAnswerSchema, { target: "openApi3" })
243
+ },
244
+ {
245
+ name: "await_task",
246
+ description: "Wait for the user's next input, then return it. Call this after notify_user to stay engaged: it polls for up to ~5 minutes (checking every few seconds) and returns { type: 'reply', threadId, notificationId, answer } when the user responds, { type: 'remind', threadId, notificationId, remindAt, remindInSeconds } when the user defers (snoozes) \u2014 call ScheduleWakeup(remindInSeconds) (it's pre-computed; if it exceeds the ~1h cap, wake at the cap and re-schedule, or use a cron), end your turn, and call await_task again when it fires \u2014 or { type: 'idle' } if nothing arrives in the window. On a reply, act on it and \u2014 if you still need the user \u2014 call notify_user again with the SAME threadId, then await_task again. On idle, call again to keep waiting, or stop and schedule a re-check. Never end a turn that still needs the user without going through notify_user + await_task.",
247
+ inputSchema: zodToJsonSchema(AwaitTaskSchema, { target: "openApi3" })
248
+ },
249
+ {
250
+ name: "set_task_state",
251
+ 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).",
252
+ inputSchema: zodToJsonSchema(SetTaskStateToolSchema, { target: "openApi3" })
253
+ }
254
+ ]
255
+ }));
256
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
257
+ switch (request.params.name) {
258
+ case "notify_user": {
259
+ const parsed = NotifyRequestSchema.parse(request.params.arguments);
260
+ const git = detectGit();
261
+ const enriched = {
262
+ ...parsed,
263
+ repo: parsed.repo ?? git.repo,
264
+ branch: parsed.branch ?? git.branch
265
+ };
266
+ const result = await submitNotification(enriched);
267
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
268
+ }
269
+ case "poll_answer": {
270
+ const { id } = PollAnswerSchema.parse(request.params.arguments);
271
+ const result = await pollAnswer(id);
272
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
273
+ }
274
+ case "await_task": {
275
+ AwaitTaskSchema.parse(request.params.arguments ?? {});
276
+ const item = await awaitTask();
277
+ return { content: [{ type: "text", text: JSON.stringify(item) }] };
278
+ }
279
+ case "set_task_state": {
280
+ const { notificationId, state } = SetTaskStateToolSchema.parse(request.params.arguments);
281
+ const result = await setTaskState(notificationId, state);
282
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
283
+ }
284
+ default:
285
+ throw new Error(`Unknown tool: ${request.params.name}`);
286
+ }
287
+ });
288
+ var transport = new StdioServerTransport();
289
+ await server.connect(transport);
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/onboard.ts
4
+ import { execFile } from "child_process";
5
+ import { mkdirSync, writeFileSync } from "fs";
6
+ import { homedir, platform } from "os";
7
+ import { join } from "path";
8
+ var BACKEND_URL = process.env.PERGY_BACKEND_URL ?? "http://localhost:3000";
9
+ var AGENT_NAME = process.env.PERGY_AGENT ?? "mcp-agent";
10
+ var TOKEN_PATH = join(homedir(), ".pergy", "token.json");
11
+ function openBrowser(url) {
12
+ const cmd = platform() === "darwin" ? "open" : platform() === "win32" ? "cmd" : "xdg-open";
13
+ const args = platform() === "win32" ? ["/c", "start", url] : [url];
14
+ execFile(cmd, args, (err) => {
15
+ if (err) {
16
+ }
17
+ });
18
+ }
19
+ function saveToken(token) {
20
+ const dir = join(homedir(), ".pergy");
21
+ mkdirSync(dir, { recursive: true });
22
+ writeFileSync(TOKEN_PATH, JSON.stringify(token, null, 2) + "\n", { mode: 384 });
23
+ }
24
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+ async function requestCode() {
26
+ const res = await fetch(`${BACKEND_URL}/api/device/code`, {
27
+ method: "POST",
28
+ headers: { "content-type": "application/json" },
29
+ body: JSON.stringify({ agent: AGENT_NAME })
30
+ });
31
+ if (!res.ok) throw new Error(`/api/device/code failed: ${res.status} ${await res.text()}`);
32
+ return await res.json();
33
+ }
34
+ async function pollToken(deviceCode) {
35
+ const res = await fetch(`${BACKEND_URL}/api/device/token`, {
36
+ method: "POST",
37
+ headers: { "content-type": "application/json" },
38
+ body: JSON.stringify({ device_code: deviceCode })
39
+ });
40
+ if (res.ok) return await res.json();
41
+ const body = await res.json().catch(() => ({ error: "unknown" }));
42
+ const err = body.error ?? "unknown";
43
+ if (err === "authorization_pending") return null;
44
+ if (err === "expired_token") throw new Error("Device code expired. Please re-run onboarding.");
45
+ if (err === "access_denied") throw new Error("Access denied by user. Onboarding cancelled.");
46
+ throw new Error(`Unexpected error from /api/device/token: ${err}`);
47
+ }
48
+ async function main() {
49
+ console.log(`
50
+ Pergy MCP onboarding (agent: "${AGENT_NAME}")
51
+ `);
52
+ const code = await requestCode();
53
+ console.log("Open this URL in your browser to approve the connection:\n");
54
+ console.log(` ${code.verification_uri_complete}
55
+ `);
56
+ console.log(` (User code: ${code.user_code})
57
+ `);
58
+ openBrowser(code.verification_uri_complete);
59
+ const intervalMs = (code.interval ?? 5) * 1e3;
60
+ const expiresAt = Date.now() + code.expires_in * 1e3;
61
+ process.stdout.write("Waiting for approval");
62
+ while (Date.now() < expiresAt) {
63
+ await sleep(intervalMs);
64
+ process.stdout.write(".");
65
+ try {
66
+ const token = await pollToken(code.device_code);
67
+ if (token !== null) {
68
+ saveToken(token);
69
+ console.log(`
70
+
71
+ Paired! Token saved to ${TOKEN_PATH} (mode 0600).`);
72
+ console.log("Treat this token like a password \u2014 it grants account access. Never log, echo, or commit it.");
73
+ console.log(` Nickname : ${token.nickname}`);
74
+ console.log(` Agent : ${token.agent}`);
75
+ console.log(` Device : ${token.device ?? "(none)"}
76
+ `);
77
+ return;
78
+ }
79
+ } catch (err) {
80
+ console.error(`
81
+
82
+ ${err.message}
83
+ `);
84
+ process.exit(1);
85
+ }
86
+ }
87
+ console.error("\n\nDevice code expired without approval. Please re-run onboarding.\n");
88
+ process.exit(1);
89
+ }
90
+ main().catch((err) => {
91
+ console.error(err.message);
92
+ process.exit(1);
93
+ });
94
+ export {
95
+ TOKEN_PATH
96
+ };
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@pergy-ai/mcp",
3
+ "version": "0.1.0",
4
+ "description": "Pergy MCP server — a voice inbox for your AI agents. Lets an agent notify a user and await their reply.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "mcp": "./dist/index.js",
9
+ "pergy-mcp": "./dist/index.js",
10
+ "pergy-mcp-onboard": "./dist/onboard.js"
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/mauurda/pergy.git",
21
+ "directory": "apps/mcp"
22
+ },
23
+ "dependencies": {
24
+ "@modelcontextprotocol/sdk": "^1.0.4",
25
+ "zod": "^3.24.1",
26
+ "zod-to-json-schema": "^3.24.1"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^22.0.0",
30
+ "tsup": "^8.3.5",
31
+ "typescript": "^5.7.2",
32
+ "vitest": "^2.1.8",
33
+ "@pergy/schema": "0.0.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup src/index.ts src/onboard.ts --format esm --clean",
37
+ "dev": "tsup src/index.ts src/onboard.ts --format esm --watch",
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "vitest run"
40
+ }
41
+ }