@requestly/mcp 1.0.4 → 1.0.5

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,409 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { askHumanToApprove, type ApprovalOutcome } from "./humanApproval.js";
8
+
9
+ /**
10
+ * RQ-3011 / RQ-3005 / RQ-3033 (Script rules) and RQ-3021 / RQ-3039 (Request and
11
+ * Response rules): code the model writes is only saved after the human has seen
12
+ * it and accepted it in the host (MCP elicitation).
13
+ *
14
+ * The rule, decided 23 Nov 2026: ask whenever the model creates a rule that has
15
+ * code, or changes the code of a saved rule. Turning a rule on or off, renaming
16
+ * it, or changing where it runs does not ask; that only ever runs code a person
17
+ * has already seen (here) or written (in the Requestly app).
18
+ *
19
+ * "Code" is everything that ends up executing or being served in the browser:
20
+ * - Script rules: each script's value (inline code, or the URL of a script to
21
+ * load) plus its tag attributes (an `onload` attribute is code too);
22
+ * - Request and Response rules: the body, code or static (a static HTML
23
+ * response can carry a <script> as well).
24
+ *
25
+ * Where the human reads the code: hosts show only part of a prompt (Claude Code
26
+ * 2.1.330 shows at most 3 lines, each cut at the terminal width, with no way to
27
+ * expand). So the prompt itself is kept to 3 short lines. Code that is one short
28
+ * line of plain ASCII is shown in the prompt. Anything else is written to a
29
+ * private file under ~/.requestly-mcp/review/, named in the prompt and opened in
30
+ * the user's default text editor. The user may edit it: what the file holds
31
+ * when they click Accept is what gets saved (decided 23 Nov). It is deleted
32
+ * afterwards.
33
+ */
34
+
35
+ export const CODE_RULE_TYPES = new Set(["Script", "Request", "Response"]);
36
+
37
+ /** Longest single line of code shown inside the prompt itself. */
38
+ export const INLINE_CODE_LIMIT = 60;
39
+
40
+ type Pair = Record<string, any>;
41
+ type Attribute = { name: string; value: string };
42
+
43
+ export type CodeItem = {
44
+ /** Identity used to tell new code from saved code. */
45
+ key: string;
46
+ /** Short label: what kind of code this is. */
47
+ label: string;
48
+ /** Where it runs, from the pair's source. */
49
+ where: string;
50
+ /** The value exactly as it will be saved (script code or URL, or body). */
51
+ value: string;
52
+ /** Script tag attributes, when the script has any. */
53
+ attributes?: Attribute[];
54
+ /** Where the value lives in the rule's pairs. */
55
+ ref: { pair: number; script?: number };
56
+ };
57
+
58
+ /** What the user accepted for each reviewed item (possibly edited in the review file). */
59
+ export type AcceptedCode = { value: string; attributes?: Attribute[] };
60
+
61
+ function describeSource(source: any): string {
62
+ if (!source || typeof source !== "object") return "(no URL match)";
63
+ return `${source.key ?? "?"} ${source.operator ?? "?"} ${JSON.stringify(String(source.value ?? "")).slice(0, 200)}`;
64
+ }
65
+
66
+ /** Everything a person reads for an item: its value, then its tag attributes. */
67
+ function shownText(item: CodeItem): string {
68
+ const attrs = item.attributes?.length
69
+ ? "\n" + item.attributes.map((a) => `[tag attribute] ${JSON.stringify(a)}`).join("\n")
70
+ : "";
71
+ return item.value + attrs;
72
+ }
73
+
74
+ /** Every piece of code a rule's pairs carry. Empty for rule types without code. */
75
+ export function codeItems(ruleType: string, pairs: unknown): CodeItem[] {
76
+ if (!CODE_RULE_TYPES.has(ruleType) || !Array.isArray(pairs)) return [];
77
+ const items: CodeItem[] = [];
78
+ (pairs as Pair[]).forEach((pair, p) => {
79
+ const where = describeSource(pair?.source);
80
+ if (ruleType === "Script") {
81
+ (Array.isArray(pair?.scripts) ? pair.scripts : []).forEach((s: any, j: number) => {
82
+ const attributes: Attribute[] = Array.isArray(s?.attributes)
83
+ ? s.attributes.map((a: any) => ({ name: String(a?.name ?? ""), value: String(a?.value ?? "") }))
84
+ : [];
85
+ const value = String(s?.value ?? "");
86
+ items.push({
87
+ key: JSON.stringify(["script", s?.codeType ?? null, s?.type ?? null, value, attributes]),
88
+ label: `${s?.codeType ?? "?"} ${s?.type === "url" ? "script loaded from a URL" : "inline code"}, ${s?.loadTime ?? "?"}`,
89
+ where,
90
+ value,
91
+ attributes: attributes.length ? attributes : undefined,
92
+ ref: { pair: p, script: j },
93
+ });
94
+ });
95
+ } else {
96
+ const part = ruleType === "Request" ? pair?.request : pair?.response;
97
+ if (part && typeof part === "object") {
98
+ const value = String(part.value ?? "");
99
+ items.push({
100
+ key: JSON.stringify([ruleType, part.type ?? null, value]),
101
+ label: `${ruleType.toLowerCase()} body (${part.type ?? "?"})`,
102
+ where,
103
+ value,
104
+ ref: { pair: p },
105
+ });
106
+ }
107
+ }
108
+ });
109
+ return items;
110
+ }
111
+
112
+ /** Items in `next` that are not already saved in `prev` (counted, so a duplicate is new too). */
113
+ export function newCode(prev: CodeItem[], next: CodeItem[]): CodeItem[] {
114
+ const counts = new Map<string, number>();
115
+ for (const p of prev) counts.set(p.key, (counts.get(p.key) ?? 0) + 1);
116
+ const added: CodeItem[] = [];
117
+ for (const n of next) {
118
+ const c = counts.get(n.key) ?? 0;
119
+ if (c > 0) counts.set(n.key, c - 1);
120
+ else added.push(n);
121
+ }
122
+ return added;
123
+ }
124
+
125
+ /**
126
+ * Put accepted (possibly edited) values back into a copy of the pairs, at the
127
+ * places the reviewed items came from.
128
+ */
129
+ export function applyAccepted(ruleType: string, pairs: unknown, items: CodeItem[], accepted: AcceptedCode[]): unknown {
130
+ const copy: Pair[] = JSON.parse(JSON.stringify(pairs));
131
+ items.forEach((item, i) => {
132
+ const a = accepted[i];
133
+ const pair = copy[item.ref.pair];
134
+ if (ruleType === "Script" && item.ref.script !== undefined) {
135
+ const script = pair.scripts[item.ref.script];
136
+ script.value = a.value;
137
+ if (item.attributes) script.attributes = a.attributes ?? [];
138
+ } else {
139
+ (ruleType === "Request" ? pair.request : pair.response).value = a.value;
140
+ }
141
+ });
142
+ return copy;
143
+ }
144
+
145
+ /** Printable ASCII only: nothing that can hide, reorder or break a line in a terminal. */
146
+ const PLAIN_ASCII = /^[\x20-\x7e]*$/;
147
+ /** Characters that can make code look different from what it is (Trojan Source and friends). */
148
+ const DECEPTIVE = /[\u0000-\u0008\u000b-\u001f\u007f\u0085\u00ad\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/;
149
+
150
+ /** One short line of plain ASCII, without attributes: safe to show in full inside the prompt. */
151
+ function fitsInline(item: CodeItem): boolean {
152
+ return !item.attributes && item.value.length <= INLINE_CODE_LIMIT && PLAIN_ASCII.test(item.value);
153
+ }
154
+
155
+ /*
156
+ * The review file. Markers carry a random nonce (unknown when the code was
157
+ * written), so code cannot fake them; the file is read back by those markers.
158
+ *
159
+ * === start of code <nonce> ===
160
+ * --- item 1 of 2 <nonce>: <label>; runs on <where> ---
161
+ * <value>
162
+ * --- tag attributes of item 1 <nonce>: one {"name","value"} JSON object per line ---
163
+ * {"name":"onload","value":"init()"}
164
+ * --- item 2 of 2 <nonce>: ... ---
165
+ * <value>
166
+ * === end of code <nonce> ===
167
+ */
168
+ function itemHeader(i: number, n: number, nonce: string, item: CodeItem): string {
169
+ return `--- item ${i} of ${n} ${nonce}: ${item.label}; runs on ${item.where} ---`;
170
+ }
171
+ function attrHeader(i: number, nonce: string): string {
172
+ return `--- tag attributes of item ${i} ${nonce}: one {"name","value"} JSON object per line ---`;
173
+ }
174
+
175
+ function renderEditable(items: CodeItem[], nonce: string): string {
176
+ const out = [`=== start of code ${nonce} ===`];
177
+ items.forEach((item, idx) => {
178
+ out.push(itemHeader(idx + 1, items.length, nonce, item), item.value);
179
+ if (item.attributes) {
180
+ // JSON per attribute, so any name or value (with "=", line breaks...) reads back exactly.
181
+ out.push(attrHeader(idx + 1, nonce), ...item.attributes.map((a) => JSON.stringify({ name: a.name, value: a.value })));
182
+ }
183
+ });
184
+ out.push(`=== end of code ${nonce} ===`);
185
+ return out.join("\n");
186
+ }
187
+
188
+ /** Read the code back out of the (possibly edited) review file; undefined if its markers are broken. */
189
+ export function parseEditable(text: string, items: CodeItem[], nonce: string): AcceptedCode[] | undefined {
190
+ const lines = text.split("\n");
191
+ // Marker lines are matched ignoring a trailing CR; code lines are kept exactly.
192
+ const bare = (l: string) => l.replace(/\r$/, "");
193
+ const start = lines.findIndex((l) => bare(l) === `=== start of code ${nonce} ===`);
194
+ const end = lines.findIndex((l) => bare(l) === `=== end of code ${nonce} ===`);
195
+ if (start < 0 || end < start) return undefined;
196
+ const body = lines.slice(start + 1, end);
197
+ const isItem = (l: string) => new RegExp(`^--- item (\\d+) of (\\d+) ${nonce}: .* ---$`).exec(bare(l));
198
+ const isAttr = (l: string) => new RegExp(`^--- tag attributes of item (\\d+) ${nonce}: .* ---$`).exec(bare(l));
199
+ const result: AcceptedCode[] = [];
200
+ let i = 0;
201
+ while (i < body.length) {
202
+ const m = isItem(body[i]);
203
+ if (!m || Number(m[1]) !== result.length + 1 || Number(m[2]) !== items.length) return undefined;
204
+ i++;
205
+ const valueLines: string[] = [];
206
+ while (i < body.length && !isItem(body[i]) && !isAttr(body[i])) valueLines.push(body[i++]);
207
+ const entry: AcceptedCode = { value: valueLines.join("\n") };
208
+ const item = items[result.length];
209
+ if (i < body.length && isAttr(body[i])) {
210
+ if (!item?.attributes || Number(isAttr(body[i])![1]) !== result.length + 1) return undefined;
211
+ i++;
212
+ const attributes: Attribute[] = [];
213
+ while (i < body.length && !isItem(body[i])) {
214
+ const line = bare(body[i++]);
215
+ if (line.trim() === "") continue;
216
+ let a: any;
217
+ try {
218
+ a = JSON.parse(line);
219
+ } catch {
220
+ return undefined;
221
+ }
222
+ if (!a || typeof a.name !== "string" || typeof a.value !== "string") return undefined;
223
+ attributes.push({ name: a.name, value: a.value });
224
+ }
225
+ entry.attributes = attributes;
226
+ } else if (item?.attributes) {
227
+ return undefined;
228
+ }
229
+ result.push(entry);
230
+ }
231
+ return result.length === items.length ? result : undefined;
232
+ }
233
+
234
+ export type CodeReviewRequest = {
235
+ /** "create" a new rule, or "update" a saved one. */
236
+ action: "create" | "update";
237
+ ruleType: string;
238
+ /** Rule name as it will be saved (model-supplied, shown quoted). */
239
+ name: string;
240
+ /** Status the rule will have after saving. */
241
+ status: string;
242
+ /** Code being added or changed (what the human must accept). */
243
+ added: CodeItem[];
244
+ /** For an update: the saved code that the new code replaces. */
245
+ replaced?: CodeItem[];
246
+ };
247
+
248
+ export type CodeReviewOutcome =
249
+ | { approved: true; accepted: AcceptedCode[]; edited: boolean }
250
+ | Exclude<ApprovalOutcome, { approved: true }>
251
+ | { approved: false; reason: "file-unreadable" };
252
+
253
+ /** ~/.requestly-mcp/review, private to the user; refuses to follow a symlink. */
254
+ function reviewDir(): string {
255
+ const base = join(homedir(), ".requestly-mcp");
256
+ const dir = join(base, "review");
257
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
258
+ for (const d of [base, dir]) {
259
+ if (lstatSync(d).isSymbolicLink()) throw new Error(`${d} is a symlink; refusing to write code for review there`);
260
+ }
261
+ chmodSync(dir, 0o700);
262
+ return dir;
263
+ }
264
+
265
+ /**
266
+ * Open the review file in the user's default app for text files, so they don't
267
+ * have to find it (terminals don't reliably make a path in the prompt
268
+ * clickable). Best effort: never blocks, never writes to stdout (the MCP channel).
269
+ * Set REQUESTLY_MCP_OPEN_REVIEW_FILE=0 to turn it off.
270
+ */
271
+ function openForReview(file: string): void {
272
+ if (process.env.REQUESTLY_MCP_OPEN_REVIEW_FILE === "0") return;
273
+ const [cmd, args] =
274
+ process.platform === "darwin"
275
+ ? ["open", [file]]
276
+ : process.platform === "win32"
277
+ ? ["explorer.exe", [file]]
278
+ : ["xdg-open", [file]];
279
+ try {
280
+ const child = spawn(cmd, args as string[], { detached: true, stdio: "ignore" });
281
+ child.on("error", (error) => console.error("Could not open the review file:", error));
282
+ child.unref();
283
+ } catch (error) {
284
+ console.error("Could not open the review file:", error);
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Ask the human to accept new code, in a prompt of at most 3 short lines.
290
+ * Short plain code is shown in the prompt; anything else is reviewed (and may
291
+ * be edited) in a private local file, and what that file holds on Accept is
292
+ * what gets saved.
293
+ */
294
+ export async function askHumanToAcceptCode(
295
+ server: McpServer,
296
+ req: CodeReviewRequest,
297
+ options: { relatedRequestId?: string | number; signal?: AbortSignal } = {}
298
+ ): Promise<CodeReviewOutcome> {
299
+ const nonce = randomBytes(6).toString("hex");
300
+ // Model-supplied name: JSON-quoted (no line breaks) and kept short so line 1 stays readable.
301
+ const shortName = req.name.length > 30 ? req.name.slice(0, 29) + "…" : req.name;
302
+ const name = JSON.stringify(shortName);
303
+ const replaced = req.action === "update" ? req.replaced ?? [] : [];
304
+ const what =
305
+ req.action === "create"
306
+ ? `Create ${req.ruleType} rule ${name} (saved ${req.status})`
307
+ : `Change the code of ${req.ruleType} rule ${name} (${req.status})`;
308
+ const unchanged = (): CodeReviewOutcome => ({
309
+ approved: true,
310
+ accepted: req.added.map((i) => ({ value: i.value, attributes: i.attributes })),
311
+ edited: false,
312
+ });
313
+
314
+ const inline =
315
+ req.added.length === 1 && replaced.length <= 1 && [...req.added, ...replaced].every(fitsInline);
316
+ if (inline) {
317
+ const lines =
318
+ req.action === "create"
319
+ ? [`${what}. Its code:`, `Code: ${req.added[0].value}`]
320
+ : [`${what}:`, `New: ${req.added[0].value}`, ...(replaced.length ? [`Was: ${replaced[0].value}`] : [])];
321
+ const outcome = await askHumanToApprove(server, lines.join("\n"), options);
322
+ return outcome.approved ? unchanged() : outcome;
323
+ }
324
+
325
+ // Review (and optionally edit) in a private local file.
326
+ const reference = replaced.length
327
+ ? "\n\nFor reference, the saved code this replaces (edits below this line are ignored):\n" +
328
+ replaced.map((r, i) => `--- saved ${i + 1} of ${replaced.length}: ${r.label}; runs on ${r.where} ---\n${shownText(r)}`).join("\n")
329
+ : "";
330
+ const review =
331
+ `Requestly MCP: ${req.action === "create" ? "create" : "change the code of"} ${req.ruleType} rule ` +
332
+ `${JSON.stringify(req.name)} (status after saving: ${req.status}).\n` +
333
+ `Read the code between the start and end lines. You may edit it: what this file holds when you ` +
334
+ `click Accept is what gets saved. Keep the marker lines as they are.\n\n` +
335
+ `${renderEditable(req.added, nonce)}${reference}\n`;
336
+ const all = [...req.added, ...replaced].map(shownText).join("\n");
337
+ const lineCount = req.added.reduce((n, i) => n + shownText(i).split("\n").length, 0);
338
+ const charCount = req.added.reduce((n, i) => n + shownText(i).length, 0);
339
+
340
+ let file: string | undefined;
341
+ try {
342
+ file = join(reviewDir(), `${nonce}.txt`);
343
+ writeFileSync(file, review, { mode: 0o600, flag: "wx" });
344
+ openForReview(file);
345
+ const warning = DECEPTIVE.test(all) ? "Has hidden or bidi characters! " : "";
346
+ const outcome = await askHumanToApprove(
347
+ server,
348
+ [
349
+ `${what}. Review or edit its code in:`,
350
+ // Alone on its line so a narrow terminal can't cut the path short.
351
+ file,
352
+ `${lineCount} line${lineCount === 1 ? "" : "s"}, ${charCount} characters. ${warning}The file's code on Accept is saved.`,
353
+ ].join("\n"),
354
+ options
355
+ );
356
+ if (!outcome.approved) return outcome;
357
+ let text: string;
358
+ try {
359
+ text = readFileSync(file, "utf8");
360
+ } catch {
361
+ return { approved: false, reason: "file-unreadable" };
362
+ }
363
+ // An editor may have re-saved the whole file with Windows line endings (no bare
364
+ // LF left, where the original had some): undo that. An unchanged file, even one
365
+ // whose code contains CRLF, is left exactly as written.
366
+ const hasBareLF = (t: string) => /(^|[^\r])\n/.test(t);
367
+ if (text !== review && !hasBareLF(text) && hasBareLF(review)) text = text.replace(/\r\n/g, "\n");
368
+ const accepted = parseEditable(text, req.added, nonce);
369
+ if (!accepted) return { approved: false, reason: "file-unreadable" };
370
+ const edited = accepted.some(
371
+ (a, i) => a.value !== req.added[i].value || JSON.stringify(a.attributes) !== JSON.stringify(req.added[i].attributes)
372
+ );
373
+ return { approved: true, accepted, edited };
374
+ } catch (error) {
375
+ console.error("Code review file could not be prepared:", error);
376
+ return { approved: false, reason: "failed" };
377
+ } finally {
378
+ if (file) rmSync(file, { force: true });
379
+ }
380
+ }
381
+
382
+ /** Tool result text when new code was not accepted. Never suggests retrying on the user's behalf. */
383
+ export function codeNotApprovedText(
384
+ what: string,
385
+ reason: Exclude<CodeReviewOutcome, { approved: true }>["reason"]
386
+ ): string {
387
+ switch (reason) {
388
+ case "unsupported":
389
+ return (
390
+ `Not saved: ${what}. This MCP host can't ask the user to approve code in a rule ` +
391
+ `(it doesn't support MCP elicitation). Rules with code can be created and edited in the ` +
392
+ `Requestly app: https://app.requestly.io/rules/my-rules`
393
+ );
394
+ case "declined":
395
+ case "cancelled":
396
+ return `Not saved: the user did not approve the code in ${what}. Nothing was changed. Do not retry unless the user asks again.`;
397
+ case "failed":
398
+ return `Not saved: the approval request for ${what} failed or timed out. Nothing was changed.`;
399
+ case "file-unreadable":
400
+ return (
401
+ `Not saved: the review file for ${what} could not be read back (it was removed, or its start, end ` +
402
+ `or item lines were changed). Nothing was changed.`
403
+ );
404
+ }
405
+ }
406
+
407
+ /** Note added to a successful result when the user edited the code before accepting. */
408
+ export const EDITED_NOTE =
409
+ "\n\nNOTE: the user edited the code before accepting; the saved code differs from what was sent. Read the rule back before changing it again.";
@@ -0,0 +1,70 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+
3
+ /**
4
+ * RQ-3008: approval that only the human can give.
5
+ *
6
+ * A `confirm: true` tool argument is supplied by the model, so a prompt-injected
7
+ * model can approve its own destructive call. Instead, the server asks the person
8
+ * directly through the host with an MCP elicitation request. The request goes from
9
+ * this server to the host and its answer comes back here; it never passes through
10
+ * the model, so the model cannot answer it.
11
+ *
12
+ * Anything other than an explicit "accept" counts as "no":
13
+ * decline, cancel, a timeout, an error, or a host that does not support elicitation.
14
+ */
15
+
16
+ export type ApprovalOutcome =
17
+ | { approved: true }
18
+ | { approved: false; reason: "unsupported" | "declined" | "cancelled" | "failed" };
19
+
20
+ /** How long the person has to answer before the action is refused. */
21
+ export const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000;
22
+
23
+ export async function askHumanToApprove(
24
+ server: McpServer,
25
+ message: string,
26
+ options: { relatedRequestId?: string | number; signal?: AbortSignal } = {}
27
+ ): Promise<ApprovalOutcome> {
28
+ if (!server.server.getClientCapabilities()?.elicitation?.form) {
29
+ return { approved: false, reason: "unsupported" };
30
+ }
31
+ try {
32
+ const result = await server.server.elicitInput(
33
+ {
34
+ mode: "form",
35
+ message,
36
+ // No form fields: the host shows the message with Accept / Decline, and
37
+ // Accept itself is the approval. (A checkbox on top of Accept was a
38
+ // redundant second step.)
39
+ requestedSchema: { type: "object", properties: {} },
40
+ },
41
+ // The caller's abort signal: if the tool call is cancelled while the prompt is
42
+ // open, a late "accept" must not delete anything.
43
+ { timeout: APPROVAL_TIMEOUT_MS, relatedRequestId: options.relatedRequestId, signal: options.signal }
44
+ );
45
+ if (result.action === "accept") {
46
+ return { approved: true };
47
+ }
48
+ return { approved: false, reason: result.action === "cancel" ? "cancelled" : "declined" };
49
+ } catch (error) {
50
+ console.error("Human approval request failed:", error);
51
+ return { approved: false, reason: "failed" };
52
+ }
53
+ }
54
+
55
+ /** Tool result text for a refused destructive action. Never suggests retrying on the user's behalf. */
56
+ export function notApprovedText(what: string, reason: Exclude<ApprovalOutcome, { approved: true }>["reason"]): string {
57
+ switch (reason) {
58
+ case "unsupported":
59
+ return (
60
+ `Not deleted: ${what}. This MCP host can't ask the user to approve a delete ` +
61
+ `(it doesn't support MCP elicitation). The user can delete it in the Requestly app: ` +
62
+ `https://app.requestly.io/rules/my-rules`
63
+ );
64
+ case "declined":
65
+ case "cancelled":
66
+ return `Not deleted: the user did not approve deleting ${what}. Do not retry unless the user asks again.`;
67
+ case "failed":
68
+ return `Not deleted: the approval request for ${what} failed or timed out. Nothing was changed.`;
69
+ }
70
+ }
package/src/index.ts CHANGED
@@ -1,25 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
- import { registerTools } from './tools/index.js';
3
+ import { createServer } from './server.js';
5
4
 
6
- const server = new McpServer({
7
- name: 'requestly-mcp-server',
8
- version: '1.0.0',
9
- description:
10
- 'MCP server for automating and managing Requestly rules, groups, and integrations via the Requestly API.',
11
- documentation: 'https://docs.requestly.io/api',
12
- capabilities: {
13
- resources: {},
14
- tools: {},
15
- // Context: This server is designed to expose Requestly API capabilities for rule and group management, CI/CD integration, and data access. Tools will allow creation, update, deletion, and retrieval of rules and groups, as well as custom workflow automation. Authentication is via x-api-key header. No tools are defined yet, but the server is ready for future expansion.
16
- },
17
- });
5
+ const server = createServer();
18
6
 
19
7
  async function main() {
20
8
  const transport = new StdioServerTransport();
21
- // Register all tools
22
- registerTools(server);
23
9
  await server.connect(transport);
24
10
  console.error('Requestly MCP Server running on stdio');
25
11
  }
package/src/server.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { registerTools } from "./tools/index.js";
3
+ import { SERVER_INSTRUCTIONS } from "./untrustedData.js";
4
+
5
+ /** The Requestly MCP server with every tool registered (RQ-3019: and its instructions). */
6
+ export function createServer(): McpServer {
7
+ const server = new McpServer(
8
+ {
9
+ name: "requestly-mcp-server",
10
+ version: "1.0.0",
11
+ description:
12
+ "MCP server for automating and managing Requestly rules, groups, and integrations via the Requestly API.",
13
+ documentation: "https://docs.requestly.io/api",
14
+ capabilities: {
15
+ resources: {},
16
+ tools: {},
17
+ },
18
+ },
19
+ { instructions: SERVER_INSTRUCTIONS }
20
+ );
21
+ registerTools(server);
22
+ return server;
23
+ }
@@ -1,5 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
+ import { REQUESTLY_API_BASE, apiErrorResult, readApiJson } from "../apiClient.js";
4
+ import { untrustedDataResult } from "../untrustedData.js";
3
5
 
4
6
  export function registerCreateGroupTool(server: McpServer) {
5
7
  server.registerTool(
@@ -26,7 +28,7 @@ export function registerCreateGroupTool(server: McpServer) {
26
28
  };
27
29
  }
28
30
  try {
29
- const response = await fetch("https://api2.requestly.io/v1/groups", {
31
+ const response = await fetch(`${REQUESTLY_API_BASE}/groups`, {
30
32
  method: "POST",
31
33
  headers: {
32
34
  "accept": "application/json",
@@ -35,15 +37,13 @@ export function registerCreateGroupTool(server: McpServer) {
35
37
  },
36
38
  body: JSON.stringify(args),
37
39
  });
38
- const data = await response.json();
39
- return {
40
- content: [
41
- {
42
- type: "text",
43
- text: JSON.stringify(data, null, 2),
44
- },
45
- ],
46
- };
40
+ if (!response.ok) {
41
+ // RQ-3025: status only — never reflect the upstream body.
42
+ return await apiErrorResult("create group", response);
43
+ }
44
+ const parsed = await readApiJson("create group", response);
45
+ if (!parsed.ok) return parsed.result;
46
+ return untrustedDataResult("create_group", parsed.data);
47
47
  } catch (error) {
48
48
  return {
49
49
  content: [