@pushary/agent-hooks 0.4.4 → 0.4.6

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/data/SKILL.md ADDED
@@ -0,0 +1,293 @@
1
+ ---
2
+ name: pushary
3
+ version: 0.1.0
4
+ description: Push notifications and human-in-the-loop for AI coding agents. Send alerts when tasks finish, ask questions (yes/no, multiple choice, or free text) via push, and get answers from the user's lock screen. Use these tools proactively — do not wait for the user to ask for notifications. Works with Cursor, Claude Code, Windsurf, Hermes, and any MCP client.
5
+ metadata:
6
+ hermes:
7
+ tags: [notifications, push, human-in-the-loop, alerts, permissions, mcp]
8
+ category: productivity
9
+ requires_toolsets: []
10
+ tags: notifications, push, mcp, human-in-the-loop, cursor, claude, windsurf, hermes, alerts, permissions
11
+ ---
12
+
13
+ # Pushary — Push Notifications for AI Agents
14
+
15
+ Pushary is an MCP server that gives you three capabilities:
16
+
17
+ 1. **Send push notifications** to the user's phone or desktop when a task finishes or an error occurs.
18
+ 2. **Ask questions** via push — yes/no, multiple choice, or free text — and wait for the user's answer.
19
+ 3. **Send rich context notifications** with file changes, error details, next steps, and embedded questions.
20
+
21
+ Use these tools proactively. Do not wait for the user to ask for notifications.
22
+
23
+ ## When to Use
24
+
25
+ **Send a notification when:**
26
+ - You finish a task that took 3 or more steps — use `context.type = "task_complete"`
27
+ - A build, test suite, or deployment fails — use `context.type = "error"` with `errorMessage`
28
+ - A long-running process completes (migration, refactor, generation)
29
+ - A status update is worth sharing — use `context.type = "info"`
30
+
31
+ **Ask with type "confirm" when:**
32
+ - You need confirmation before a destructive or irreversible action
33
+ - Binary decision: proceed or abort
34
+
35
+ **Ask with type "select" when:**
36
+ - Multiple implementation approaches exist (2-6 options)
37
+ - The user needs to pick from a known set
38
+
39
+ **Ask with type "input" when:**
40
+ - You need a name, path, value, or free-text decision
41
+ - The options cannot be enumerated in advance
42
+
43
+ **Do NOT notify when:**
44
+ - The task is trivial or single-step
45
+ - The question can be answered from context without user input
46
+ - You already sent 3 notifications for the current task (unless the user explicitly asked for more)
47
+
48
+ ## Setup
49
+
50
+ Add Pushary to your MCP configuration:
51
+
52
+ ```json
53
+ {
54
+ "mcpServers": {
55
+ "pushary": {
56
+ "url": "https://pushary.com/api/mcp/mcp"
57
+ }
58
+ }
59
+ }
60
+ ```
61
+
62
+ Sign up at https://pushary.com/sign-up?from=ai-coding to get your API key.
63
+
64
+ ## Tools
65
+
66
+ ### send_notification
67
+
68
+ Send a one-way push notification to the user. Optionally include structured context for a rich detail page.
69
+
70
+ **Parameters:**
71
+
72
+ | Name | Type | Required | Description |
73
+ |------|------|----------|-------------|
74
+ | title | string | Yes | Notification title (max 100 chars, aim for under 60) |
75
+ | body | string | Yes | Notification body (max 500 chars, aim for under 200) |
76
+ | url | string | No | URL opened when tapped. Ignored if context is provided. |
77
+ | agentName | string | No | Identifies which agent sent this (e.g., "Claude Code - myproject") |
78
+ | iconUrl | string | No | Custom notification icon URL |
79
+ | imageUrl | string | No | Large image shown in the notification |
80
+ | subscriberIds | string[] | No | Target specific subscriber IDs |
81
+ | externalIds | string[] | No | Target by external IDs |
82
+ | tags | string[] | No | Target by subscriber tags |
83
+ | context | object | No | Structured context for a rich detail page (see below) |
84
+
85
+ **Context object:**
86
+
87
+ | Name | Type | Description |
88
+ |------|------|-------------|
89
+ | type | "task_complete" / "error" / "info" | The kind of notification |
90
+ | summary | string | Short summary of what happened |
91
+ | details | string[] | Bullet-point details |
92
+ | filesChanged | string[] | List of files that were changed |
93
+ | errorMessage | string | Error message (for error type) |
94
+ | errorFile | string | File path where the error occurred |
95
+ | nextSteps | string | Suggested next steps for the user |
96
+ | askQuestion | object | Embed a decision prompt in the notification (see below) |
97
+
98
+ **Embedded askQuestion:**
99
+
100
+ | Name | Type | Description |
101
+ |------|------|-------------|
102
+ | question | string | A follow-up question shown below the context |
103
+ | type | "confirm" / "select" / "input" | Question type (default: confirm) |
104
+ | options | string[] | Options for select type (2-6 items) |
105
+
106
+ When `askQuestion` is provided, the response includes a `linkedCorrelationId` you pass to `wait_for_answer`.
107
+
108
+ **Example — task completed with context:**
109
+
110
+ ```json
111
+ {
112
+ "title": "Refactoring complete",
113
+ "body": "Extracted 3 shared components across 12 files",
114
+ "agentName": "Claude Code - pushary repo",
115
+ "context": {
116
+ "type": "task_complete",
117
+ "summary": "Extracted shared Button, Modal, and Card components from 12 files",
118
+ "filesChanged": ["src/components/Button.tsx", "src/components/Modal.tsx", "src/components/Card.tsx"],
119
+ "nextSteps": "Run the test suite to verify no regressions"
120
+ }
121
+ }
122
+ ```
123
+
124
+ **Example — error with embedded question:**
125
+
126
+ ```json
127
+ {
128
+ "title": "Build failed",
129
+ "body": "TypeScript error in auth.ts:42",
130
+ "agentName": "Claude Code - api-server",
131
+ "context": {
132
+ "type": "error",
133
+ "errorMessage": "Type 'string' is not assignable to type 'AuthToken'",
134
+ "errorFile": "src/auth.ts:42",
135
+ "summary": "The auth token type changed upstream and this file needs updating",
136
+ "askQuestion": {
137
+ "question": "Should I update the type or revert the upstream change?",
138
+ "type": "select",
139
+ "options": ["Update the type in auth.ts", "Revert the upstream change", "Skip for now"]
140
+ }
141
+ }
142
+ }
143
+ ```
144
+
145
+ ### ask_user
146
+
147
+ Send a question to the user via push notification. Supports three question types. Returns a `correlationId` that you pass to `wait_for_answer` to get the response.
148
+
149
+ **Parameters:**
150
+
151
+ | Name | Type | Required | Description |
152
+ |------|------|----------|-------------|
153
+ | question | string | Yes | The question to ask (max 500 chars) |
154
+ | type | "confirm" / "select" / "input" | No | Question type (default: confirm) |
155
+ | options | string[] | No | Choices for select type (2-6 options). Required when type is select. |
156
+ | placeholder | string | No | Placeholder text for input type (max 200 chars) |
157
+ | context | string | No | What the agent is working on, shown above the question (max 500 chars) |
158
+ | agentName | string | No | Identifies which agent is asking (e.g., "Claude Code - myproject") |
159
+ | callbackUrl | string | No | Webhook URL to POST the answer to when the user responds |
160
+ | subscriberIds | string[] | No | Target specific subscriber IDs |
161
+ | externalIds | string[] | No | Target by external IDs |
162
+ | tags | string[] | No | Target by subscriber tags |
163
+
164
+ **Returns:** `{ "correlationId": "uuid", "status": "pending", "expiresInSeconds": 600 }`
165
+
166
+ **Example — confirm (yes/no):**
167
+
168
+ ```json
169
+ {
170
+ "question": "Delete the 3 unused migration files?",
171
+ "type": "confirm",
172
+ "context": "Cleaning up old database migrations in db/migrate/",
173
+ "agentName": "Claude Code - myproject"
174
+ }
175
+ ```
176
+
177
+ **Example — select (multiple choice):**
178
+
179
+ ```json
180
+ {
181
+ "question": "Which auth strategy should I use?",
182
+ "type": "select",
183
+ "options": ["JWT tokens", "Session cookies", "OAuth2 + PKCE"],
184
+ "context": "Setting up authentication for the new API endpoints",
185
+ "agentName": "Claude Code - api-server"
186
+ }
187
+ ```
188
+
189
+ **Example — input (free text):**
190
+
191
+ ```json
192
+ {
193
+ "question": "What should the new API endpoint path be?",
194
+ "type": "input",
195
+ "placeholder": "/api/v2/...",
196
+ "context": "Creating a new REST endpoint for user preferences",
197
+ "agentName": "Cursor - frontend"
198
+ }
199
+ ```
200
+
201
+ ### wait_for_answer
202
+
203
+ Long-poll for the user's response to a question sent via `ask_user`. Blocks until the user responds or the timeout is reached.
204
+
205
+ **Parameters:**
206
+
207
+ | Name | Type | Required | Description |
208
+ |------|------|----------|-------------|
209
+ | correlationId | string (uuid) | Yes | The correlationId from ask_user |
210
+ | timeoutMs | integer | No | How long to wait (default 30000, max 55000) |
211
+
212
+ **Returns:**
213
+ - `{ "answered": true, "value": "yes" }` — user responded
214
+ - `{ "answered": false }` — timeout reached, no answer yet
215
+
216
+ ### cancel_question
217
+
218
+ Cancel a pending question so it can no longer be answered. Use when the question becomes irrelevant (e.g., you found the answer another way or the user responded in chat).
219
+
220
+ **Parameters:**
221
+
222
+ | Name | Type | Required | Description |
223
+ |------|------|----------|-------------|
224
+ | correlationId | string (uuid) | Yes | The correlationId of the question to cancel |
225
+
226
+ ## Permission Gating (REQUIRED)
227
+
228
+ Before executing any of the following, you MUST call `ask_user` with type "confirm" and wait for approval. Do NOT proceed without an explicit "yes" from the user:
229
+
230
+ - File deletion (`rm`, `unlink`, any destructive file operation)
231
+ - Database mutations (`DROP`, `DELETE`, `TRUNCATE`, migrations)
232
+ - Deployment commands (`deploy`, `push`, `publish`, `release`)
233
+ - System administration (`systemctl`, `service`, package install/remove)
234
+ - Git operations that rewrite history (`reset --hard`, `push --force`, `rebase`)
235
+ - Network configuration changes (firewall, DNS, proxy)
236
+ - Any command the user has flagged as dangerous
237
+
238
+ If `wait_for_answer` returns `answered: false` after 3 attempts, do NOT execute the command. Notify the user that the operation was skipped due to no response.
239
+
240
+ This is not optional. Treat it as a hard constraint, not a suggestion.
241
+
242
+ ## Human-in-the-Loop Flow
243
+
244
+ Follow this exact sequence when you need a decision from the user:
245
+
246
+ 1. Call `ask_user` with a clear, concise question and the appropriate type.
247
+ 2. Immediately call `wait_for_answer` with the returned `correlationId` and `timeoutMs: 55000`.
248
+ 3. If `wait_for_answer` returns `{ "answered": false }`, retry the same `wait_for_answer` call up to 3 times. The answer persists in Redis for 10 minutes, so it will be there when the user responds.
249
+ 4. Once you receive `{ "answered": true, "value": "..." }`, act on the decision.
250
+ 5. If the user answers in chat before the push response arrives, continue normally and call `cancel_question` to clean up.
251
+
252
+ **Pseudocode:**
253
+
254
+ ```
255
+ result = ask_user({
256
+ question: "Which auth strategy should I use?",
257
+ type: "select",
258
+ options: ["JWT tokens", "Session cookies", "OAuth2 + PKCE"],
259
+ context: "Setting up authentication for the new API",
260
+ agentName: "Claude Code - myproject"
261
+ })
262
+ correlationId = result.correlationId
263
+
264
+ for attempt in 1..3:
265
+ answer = wait_for_answer({ correlationId, timeoutMs: 55000 })
266
+ if answer.answered:
267
+ // answer.value = "JWT tokens" (the selected option)
268
+ // proceed with the chosen approach
269
+ break
270
+
271
+ if not answer.answered after 3 attempts:
272
+ // user did not respond — pick the safe default or ask in chat
273
+ ```
274
+
275
+ ## Identifying Your Agent
276
+
277
+ Always pass `agentName` when you are one of multiple possible agents the user may be running. The user sees this in the notification title to know which agent is asking.
278
+
279
+ **Format:** `{Agent Type} - {project or context}`
280
+
281
+ **Examples:**
282
+ - `"Claude Code - pushary repo"`
283
+ - `"Hermes - daily-briefing"`
284
+ - `"Cursor - frontend refactor"`
285
+
286
+ ## Notification Etiquette
287
+
288
+ - **Titles under 60 characters.** They get truncated on phone lock screens.
289
+ - **Bodies under 200 characters.** Concise summaries, not full explanations.
290
+ - **Max 3 notifications per task** unless the user explicitly requests more.
291
+ - **Use context for detail.** Put file lists, error traces, and next steps in the context object — not the notification body.
292
+ - **Write questions as if talking to a busy person.** The user is on their phone, possibly away from their computer. Be specific: "Delete the 3 unused migration files?" is better than "Should I clean up?"
293
+ - **Pick the right question type.** Use confirm for binary decisions, select when options are known, input when they are not.
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ removeClaudeMcpServers,
4
+ removePusharySettings
5
+ } from "../chunk-AC4UYAGX.js";
2
6
 
3
7
  // bin/pushary-clean.ts
4
8
  import { existsSync, readFileSync, writeFileSync, rmSync } from "fs";
@@ -28,56 +32,13 @@ var readJson = (path) => {
28
32
  var writeJson = (path, data) => {
29
33
  writeFileSync(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
30
34
  };
31
- var isPusharyPermission = (rule) => rule.includes("pushary") || rule.includes("MCP(pushary");
32
- var isPusharyHook = (entry) => {
33
- const hooks = entry.hooks;
34
- if (!hooks) return false;
35
- return hooks.some((h) => {
36
- const cmd = String(h.command ?? "");
37
- return cmd.includes("pushary-hook") || cmd.includes("pushary-post-hook") || cmd.includes("pushary-stop-hook");
38
- });
39
- };
40
35
  var cleanSettingsFile = (path, label) => {
41
36
  const data = readJson(path);
42
37
  if (!data) {
43
38
  console.log(` ${skip} ${label} ${dim("(not found)")}`);
44
39
  return;
45
40
  }
46
- let changed = false;
47
- const mcpServers = data.mcpServers;
48
- if (mcpServers?.pushary) {
49
- delete mcpServers.pushary;
50
- if (Object.keys(mcpServers).length === 0) delete data.mcpServers;
51
- changed = true;
52
- }
53
- const permissions = data.permissions;
54
- if (permissions?.allow) {
55
- const allow = permissions.allow;
56
- const filtered = allow.filter((r) => !isPusharyPermission(r));
57
- if (filtered.length !== allow.length) {
58
- permissions.allow = filtered;
59
- if (filtered.length === 0) delete permissions.allow;
60
- if (Object.keys(permissions).length === 0) delete data.permissions;
61
- changed = true;
62
- }
63
- }
64
- const hooks = data.hooks;
65
- if (hooks) {
66
- for (const key of ["PreToolUse", "PostToolUse", "Stop"]) {
67
- const entries = hooks[key];
68
- if (!entries) continue;
69
- const filtered = entries.filter((e) => !isPusharyHook(e));
70
- if (filtered.length !== entries.length) {
71
- if (filtered.length === 0) {
72
- delete hooks[key];
73
- } else {
74
- hooks[key] = filtered;
75
- }
76
- changed = true;
77
- }
78
- }
79
- if (Object.keys(hooks).length === 0) delete data.hooks;
80
- }
41
+ const changed = removePusharySettings(data);
81
42
  if (changed) {
82
43
  writeJson(path, data);
83
44
  console.log(` ${check} ${label} ${dim("(cleaned)")}`);
@@ -100,15 +61,14 @@ var main = async () => {
100
61
  cleanSettingsFile(CLAUDE_SETTINGS_LOCAL, "Claude Code settings.local");
101
62
  const claudeJson = readJson(CLAUDE_JSON);
102
63
  if (claudeJson) {
103
- const mcpServers = claudeJson.mcpServers;
104
- if (mcpServers?.pushary) {
105
- delete mcpServers.pushary;
106
- if (Object.keys(mcpServers).length === 0) delete claudeJson.mcpServers;
64
+ if (removeClaudeMcpServers(claudeJson)) {
107
65
  writeJson(CLAUDE_JSON, claudeJson);
108
- console.log(` ${check} Claude Code MCP server ${dim("(removed from ~/.claude.json)")}`);
66
+ console.log(` ${check} Claude Code MCP servers ${dim("(removed from ~/.claude.json)")}`);
109
67
  } else {
110
- console.log(` ${skip} Claude Code MCP server ${dim("(not in ~/.claude.json)")}`);
68
+ console.log(` ${skip} Claude Code MCP servers ${dim("(no pushary entries)")}`);
111
69
  }
70
+ } else {
71
+ console.log(` ${skip} Claude Code MCP servers ${dim("(not found)")}`);
112
72
  }
113
73
  const cursorData = readJson(CURSOR_MCP);
114
74
  if (cursorData) {
@@ -2,7 +2,8 @@
2
2
  import {
3
3
  askUser,
4
4
  waitForAnswer
5
- } from "../chunk-4TWRLEOX.js";
5
+ } from "../chunk-M5SRSBLS.js";
6
+ import "../chunk-RJKW6LLC.js";
6
7
  import {
7
8
  reportEvent
8
9
  } from "../chunk-EQE6Z4YQ.js";
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ callMcpTool,
4
+ sendMcpRequest
5
+ } from "../chunk-RJKW6LLC.js";
6
+ import "../chunk-VUNL35KE.js";
2
7
 
3
8
  // bin/pushary-doctor.ts
4
9
  import { existsSync, readFileSync } from "fs";
@@ -16,7 +21,6 @@ var fail = red("\u2717");
16
21
  var warn = yellow("!");
17
22
  var CLAUDE_SETTINGS = join(homedir(), ".claude", "settings.json");
18
23
  var SKILL_PATH = join(homedir(), ".claude", "skills", "pushary", "SKILL.md");
19
- var MCP_URL = "https://pushary.com/api/mcp/mcp";
20
24
  var readJson = (path) => {
21
25
  try {
22
26
  return JSON.parse(readFileSync(path, "utf-8"));
@@ -38,14 +42,16 @@ var main = async () => {
38
42
  console.log(` ${dim("Configuration")}`);
39
43
  const apiKey = process.env.PUSHARY_API_KEY;
40
44
  check(!!apiKey, "API key in environment", apiKey ? `pk_${apiKey.split(".")[0]?.slice(3, 7)}...` : "PUSHARY_API_KEY not set");
45
+ const CLAUDE_JSON = join(homedir(), ".claude.json");
46
+ const claudeJson = readJson(CLAUDE_JSON);
47
+ const mcpServers = claudeJson?.mcpServers ?? {};
48
+ const pusharyServer = mcpServers?.pushary;
49
+ check(!!pusharyServer, "Claude Code: MCP server configured");
50
+ if (pusharyServer) {
51
+ check(pusharyServer.type === "http", "Claude Code: MCP server type", pusharyServer.type ? String(pusharyServer.type) : 'missing \u2014 add type: "http"');
52
+ }
41
53
  const settings = readJson(CLAUDE_SETTINGS);
42
54
  if (settings) {
43
- const mcpServers = settings.mcpServers;
44
- const pusharyServer = mcpServers?.pushary;
45
- check(!!pusharyServer, "Claude Code: MCP server configured");
46
- if (pusharyServer) {
47
- check(pusharyServer.type === "http", "Claude Code: MCP server type", pusharyServer.type ? String(pusharyServer.type) : 'missing \u2014 add type: "http"');
48
- }
49
55
  const hooks = settings.hooks;
50
56
  const hasPreHook = JSON.stringify(hooks?.PreToolUse ?? []).includes("pushary-hook");
51
57
  const hasPostHook = JSON.stringify(hooks?.PostToolUse ?? []).includes("pushary-post-hook");
@@ -54,8 +60,8 @@ var main = async () => {
54
60
  check(hasPostHook, "Claude Code: PostToolUse hook");
55
61
  check(hasStopHook, "Claude Code: Stop hook");
56
62
  const permissions = settings.permissions;
57
- const hasWildcard = permissions?.allow?.some((r) => r === "MCP(pushary:*)") ?? false;
58
- check(hasWildcard, "Claude Code: Pushary tools auto-allowed", hasWildcard ? "MCP(pushary:*)" : "missing");
63
+ const hasWildcard = permissions?.allow?.some((r) => r === "mcp__pushary__*" || r === "MCP(pushary:*)") ?? false;
64
+ check(hasWildcard, "Claude Code: Pushary tools auto-allowed", hasWildcard ? "mcp__pushary__*" : "missing");
59
65
  const hasLegacyPerms = permissions?.allow?.some((r) => r.startsWith("mcp__pushary__")) ?? false;
60
66
  if (hasLegacyPerms) {
61
67
  console.log(` ${warn} Legacy individual permissions detected ${dim("(run pushary clean, then setup again)")}`);
@@ -79,72 +85,36 @@ var main = async () => {
79
85
  check(false, "MCP handshake", "skipped");
80
86
  } else {
81
87
  let sessionId = "";
82
- let toolCount = 0;
83
88
  try {
84
- const initRes = await fetch(MCP_URL, {
85
- method: "POST",
86
- headers: {
87
- "Content-Type": "application/json",
88
- "Accept": "application/json, text/event-stream",
89
- "Authorization": `Bearer ${apiKey}`
90
- },
91
- body: JSON.stringify({
92
- jsonrpc: "2.0",
93
- id: 1,
94
- method: "initialize",
95
- params: {
96
- protocolVersion: "2025-03-26",
97
- capabilities: {},
98
- clientInfo: { name: "pushary-doctor", version: "1.0" }
99
- }
100
- }),
101
- signal: AbortSignal.timeout(1e4)
102
- });
103
- check(initRes.ok, "MCP server reachable", `${initRes.status} ${initRes.statusText}`);
104
- sessionId = initRes.headers.get("mcp-session-id") ?? "";
89
+ const initResult = await sendMcpRequest(apiKey, {
90
+ jsonrpc: "2.0",
91
+ id: 1,
92
+ method: "initialize",
93
+ params: {
94
+ protocolVersion: "2025-03-26",
95
+ capabilities: {},
96
+ clientInfo: { name: "pushary-doctor", version: "1.0" }
97
+ }
98
+ }, { timeoutMs: 1e4 });
99
+ check(true, "MCP server reachable", `${initResult.status} ${initResult.statusText}`);
100
+ sessionId = initResult.sessionId;
105
101
  if (sessionId) {
106
102
  console.log(` ${pass} Session ID returned ${dim(`(${sessionId.slice(0, 8)}...)`)}`);
107
103
  } else {
108
104
  console.log(` ${dim("\u2013")} Stateless mode ${dim("(no session ID)")}`);
109
105
  }
110
- const initBody = await initRes.text();
111
- const initMatch = initBody.match(/data: (.+)/);
112
- if (initMatch) {
113
- const initData = JSON.parse(initMatch[1]);
114
- check(!!initData.result?.serverInfo, "API key valid", initData.result?.serverInfo?.name ?? "unknown server");
115
- }
116
- const toolsRes = await fetch(MCP_URL, {
117
- method: "POST",
118
- headers: {
119
- "Content-Type": "application/json",
120
- "Accept": "application/json, text/event-stream",
121
- "Authorization": `Bearer ${apiKey}`,
122
- ...sessionId ? { "Mcp-Session-Id": sessionId } : {}
123
- },
124
- body: JSON.stringify({
125
- jsonrpc: "2.0",
126
- id: 2,
127
- method: "tools/list",
128
- params: {}
129
- }),
130
- signal: AbortSignal.timeout(1e4)
106
+ check(!!initResult.data.result?.serverInfo, "API key valid", initResult.data.result?.serverInfo?.name ?? "unknown server");
107
+ const toolsResult = await sendMcpRequest(apiKey, {
108
+ jsonrpc: "2.0",
109
+ id: 2,
110
+ method: "tools/list",
111
+ params: {}
112
+ }, {
113
+ sessionId,
114
+ timeoutMs: 1e4
131
115
  });
132
- const toolsBody = await toolsRes.text();
133
- if (!toolsRes.ok) {
134
- try {
135
- const errData = JSON.parse(toolsBody);
136
- check(false, "MCP tools discovered", `${toolsRes.status}: ${errData.error?.message ?? toolsBody}`);
137
- } catch {
138
- check(false, "MCP tools discovered", `${toolsRes.status} ${toolsRes.statusText}`);
139
- }
140
- } else {
141
- const toolsMatch = toolsBody.match(/data: (.+)/);
142
- if (toolsMatch) {
143
- const toolsData = JSON.parse(toolsMatch[1]);
144
- toolCount = toolsData.result?.tools?.length ?? 0;
145
- }
146
- check(toolCount > 0, "MCP tools discovered", `${toolCount} tools`);
147
- }
116
+ const toolCount = toolsResult.data.result?.tools?.length ?? 0;
117
+ check(toolCount > 0, "MCP tools discovered", `${toolCount} tools`);
148
118
  } catch (err) {
149
119
  const msg = err instanceof Error ? err.message : "unknown error";
150
120
  check(false, "MCP server reachable", msg);
@@ -174,71 +144,28 @@ var main = async () => {
174
144
  console.log();
175
145
  console.log(` ${dim("Question Roundtrip")}`);
176
146
  try {
177
- const mcpHeaders = {
178
- "Content-Type": "application/json",
179
- "Accept": "application/json, text/event-stream",
180
- "Authorization": `Bearer ${apiKey}`,
181
- ...sessionId ? { "Mcp-Session-Id": sessionId } : {}
182
- };
183
- const askRes = await fetch(MCP_URL, {
184
- method: "POST",
185
- headers: mcpHeaders,
186
- body: JSON.stringify({
187
- jsonrpc: "2.0",
188
- id: 3,
189
- method: "tools/call",
190
- params: {
191
- name: "ask_user",
192
- arguments: {
193
- question: "Pushary Doctor: tap Yes to verify the roundtrip works.",
194
- type: "confirm",
195
- agentName: "Pushary Doctor"
196
- }
197
- }
198
- }),
199
- signal: AbortSignal.timeout(15e3)
147
+ const askResult = await callMcpTool(apiKey, "ask_user", {
148
+ question: "Pushary Doctor: tap Yes to verify the roundtrip works.",
149
+ type: "confirm",
150
+ agentName: "Pushary Doctor"
151
+ }, {
152
+ id: 3,
153
+ sessionId,
154
+ timeoutMs: 15e3
200
155
  });
201
- const askBody = await askRes.text();
202
- const askMatch = askBody.match(/data: (.+)/);
203
- let correlationId = "";
204
- if (askMatch) {
205
- const askData = JSON.parse(askMatch[1]);
206
- const content = askData.result?.content?.[0]?.text;
207
- if (content) {
208
- const parsed = JSON.parse(content);
209
- correlationId = parsed.correlationId;
210
- }
211
- }
212
- if (correlationId) {
156
+ if (askResult.correlationId) {
213
157
  console.log(` ${dim("\u2192")} Question sent, waiting for your answer...`);
214
158
  const start = Date.now();
215
- const waitRes = await fetch(MCP_URL, {
216
- method: "POST",
217
- headers: mcpHeaders,
218
- body: JSON.stringify({
219
- jsonrpc: "2.0",
220
- id: 4,
221
- method: "tools/call",
222
- params: {
223
- name: "wait_for_answer",
224
- arguments: { correlationId, timeoutMs: 55e3 }
225
- }
226
- }),
227
- signal: AbortSignal.timeout(6e4)
159
+ const waitResult = await callMcpTool(apiKey, "wait_for_answer", {
160
+ correlationId: askResult.correlationId,
161
+ timeoutMs: 55e3
162
+ }, {
163
+ id: 4,
164
+ sessionId,
165
+ timeoutMs: 6e4
228
166
  });
229
- const waitBody = await waitRes.text();
230
- const waitMatch = waitBody.match(/data: (.+)/);
231
- if (waitMatch) {
232
- const waitData = JSON.parse(waitMatch[1]);
233
- const content = waitData.result?.content?.[0]?.text;
234
- if (content) {
235
- const parsed = JSON.parse(content);
236
- const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
237
- check(parsed.answered === true, "Answer received", `"${parsed.value}" (${elapsed}s roundtrip)`);
238
- } else {
239
- check(false, "Answer received", "no response within timeout");
240
- }
241
- }
167
+ const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
168
+ check(waitResult.answered === true, "Answer received", waitResult.answered ? `"${waitResult.value}" (${elapsed}s roundtrip)` : "no response within timeout");
242
169
  } else {
243
170
  check(false, "Question sent", "failed to get correlationId");
244
171
  }
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  handlePreToolUse
4
- } from "../chunk-KINE5LNQ.js";
5
- import "../chunk-4TWRLEOX.js";
4
+ } from "../chunk-4TQW4K6T.js";
5
+ import "../chunk-M5SRSBLS.js";
6
+ import "../chunk-RJKW6LLC.js";
6
7
  import "../chunk-VUNL35KE.js";
7
8
 
8
9
  // bin/pushary-hook.ts