@plune-ai/cli 0.39.6 → 0.39.7

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,1266 @@
1
+ // src/mcp/http.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { createMcpHandler } from "@modelcontextprotocol/server";
4
+
5
+ // src/mcp/server.ts
6
+ import { Transform } from "stream";
7
+ import { StringDecoder } from "string_decoder";
8
+ import { McpServer, PROTOCOL_VERSION_META_KEY, UnsupportedProtocolVersionError } from "@modelcontextprotocol/server";
9
+ import { z as z4 } from "zod";
10
+ import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
11
+
12
+ // src/mcp-tools/contract.ts
13
+ import { z as z2 } from "zod";
14
+
15
+ // src/mcp-tools/schemas.ts
16
+ import { z } from "zod";
17
+ var BATCH_MAX = 100;
18
+ var isHttp = (s) => {
19
+ try {
20
+ const u = new URL(s);
21
+ return u.protocol === "http:" || u.protocol === "https:";
22
+ } catch {
23
+ return false;
24
+ }
25
+ };
26
+ var httpLink = (what, max) => z.string().trim().min(1, `${what} is empty`).max(max).refine(isHttp, `${what} must be an http or https address`);
27
+ var id = (what) => z.string().min(1).describe(what);
28
+ var dryRun = z.boolean().optional().describe("true: answer what would be sent, and send nothing");
29
+ var MISSION_STATES = ["draft", "active", "done"];
30
+ var MISSION_DOCUMENTATION = ["unknown", "provided", "none"];
31
+ var MISSION_LINK_KINDS = ["url", "openapi", "repo", "ticket"];
32
+ var missionName = z.string().trim().min(1, "a mission needs a name").max(200);
33
+ var missionSummary = z.string().trim().max(2e3).describe("What the product is, in 3-5 sentences");
34
+ var missionUrl = httpLink("url", 2048).nullable().describe("Where the product runs; null takes it off");
35
+ var missionFields = {
36
+ name: missionName,
37
+ summary: missionSummary.optional(),
38
+ url: missionUrl.optional(),
39
+ state: z.enum(MISSION_STATES).optional(),
40
+ documentation: z.enum(MISSION_DOCUMENTATION).optional().describe("Is there documentation: provided (it is among the sources), none, or unknown")
41
+ };
42
+ var sourceTitle = z.string().trim().min(1).max(200);
43
+ var sourceVersion = z.string().trim().min(1).max(200).describe("A commit, a tag, a revision, an ETag");
44
+ var linkSource = z.strictObject({
45
+ missionId: id("The mission"),
46
+ kind: z.enum(MISSION_LINK_KINDS),
47
+ ref: httpLink("ref", 2048).describe("The link"),
48
+ title: sourceTitle.optional(),
49
+ version: sourceVersion.optional(),
50
+ dry_run: dryRun
51
+ });
52
+ var fileSource = z.strictObject({
53
+ missionId: id("The mission"),
54
+ kind: z.literal("file"),
55
+ name: z.string().trim().min(1).max(200).regex(/\.(txt|md|markdown|json)$/i, "a source file is .txt, .md, .markdown or .json").describe("The file name; its extension sets the type"),
56
+ text: z.string().max(1048576).describe("The whole text of the file, UTF-8, at most 1 MiB"),
57
+ title: sourceTitle.optional(),
58
+ version: sourceVersion.optional(),
59
+ dry_run: dryRun
60
+ });
61
+ var ACCESS_KINDS = ["openapi", "repo", "staging", "har"];
62
+ var questionText = z.string().trim().min(1).max(2e3);
63
+ var questionInput = z.strictObject({
64
+ template: z.enum(["plain", "access"]).describe("plain: a question with up to three options; access: ask for an API description, the code, a staging host or a HAR file"),
65
+ text: questionText,
66
+ missionId: z.string().min(1).optional(),
67
+ options: z.array(z.string().trim().min(1).max(200)).min(1).max(3).refine((o) => new Set(o).size === o.length, { message: "no two options are the same" }).optional().describe("plain only: what the person may pick from"),
68
+ access: z.array(z.enum(ACCESS_KINDS)).min(1).max(ACCESS_KINDS.length).refine((a) => new Set(a).size === a.length, { message: "an access kind is named once" }).optional().describe("access only: what you ask to be given"),
69
+ dry_run: dryRun
70
+ });
71
+ var STRATEGY_SOURCE_KINDS = ["mission-source", "doc-section", "screen", "endpoint", "requirement", "url"];
72
+ var TEST_LEVELS = ["component", "component-integration", "system", "system-integration", "acceptance"];
73
+ var QUALITY_CHARACTERISTICS = [
74
+ "functional-suitability",
75
+ "performance-efficiency",
76
+ "compatibility",
77
+ "interaction-capability",
78
+ "reliability",
79
+ "security",
80
+ "maintainability",
81
+ "flexibility",
82
+ "safety"
83
+ ];
84
+ var TEST_TECHNIQUES = [
85
+ "equivalence-partitioning",
86
+ "boundary-value",
87
+ "decision-table",
88
+ "state-transition",
89
+ "statement",
90
+ "branch",
91
+ "error-guessing",
92
+ "exploratory",
93
+ "checklist"
94
+ ];
95
+ var RISK_SCALE = ["low", "medium", "high"];
96
+ var itemFields = {
97
+ text: z.string().trim().min(1).max(1e3).describe("Markdown"),
98
+ source: z.strictObject({ kind: z.enum(STRATEGY_SOURCE_KINDS), ref: z.string().trim().min(1).max(300) }).optional().describe("Where it was read"),
99
+ assumption: z.literal(true).optional().describe("You assumed it: a person confirms"),
100
+ waitingOn: z.string().min(1).optional().describe("The id of an open question of this mission it waits for")
101
+ };
102
+ var strategyItem = z.strictObject(itemFields);
103
+ var items = z.array(strategyItem).min(1).max(25);
104
+ var unique = (values) => z.array(z.enum(values)).min(1).refine((a) => new Set(a).size === a.length, { message: "named once" });
105
+ var linkIds = z.array(z.string().min(1)).max(50).refine((a) => new Set(a).size === a.length, { message: "an id is named once" });
106
+ var share = z.number().int().min(0).max(100);
107
+ var strategyContent = z.strictObject({
108
+ objectives: items,
109
+ scope: z.strictObject({ in: items, out: items.describe("What is deliberately not tested, and why") }),
110
+ approach: items,
111
+ profile: z.strictObject({
112
+ levels: unique(TEST_LEVELS),
113
+ characteristics: unique(QUALITY_CHARACTERISTICS),
114
+ techniques: unique(TEST_TECHNIQUES),
115
+ split: z.strictObject({ api: share, ui: share, manual: share }).refine((s) => s.api + s.ui + s.manual === 100, { message: "the split of api, ui and manual adds up to 100" }),
116
+ notes: items
117
+ }),
118
+ risks: z.array(
119
+ z.strictObject({
120
+ ...itemFields,
121
+ likelihood: z.enum(RISK_SCALE),
122
+ impact: z.enum(RISK_SCALE),
123
+ caseIds: linkIds.optional(),
124
+ requirementIds: linkIds.optional()
125
+ })
126
+ ).min(1).max(50),
127
+ entryCriteria: items,
128
+ exitCriteria: items
129
+ });
130
+ var SOURCE_REF_KINDS = ["url", "openapi-operation", "requirement", "pasted-text"];
131
+ var proposedCase = z.strictObject({
132
+ title: z.string().trim().min(1).max(300),
133
+ steps: z.array(z.string().trim().min(1).max(400)).min(1).max(20),
134
+ expected: z.string().trim().min(1).max(2e3),
135
+ execution: z.enum(["auto", "manual"]).optional().describe("auto: can be automated; manual (default): stays with a person"),
136
+ technique: z.string().min(1).max(32).optional(),
137
+ priority: z.string().min(1).optional(),
138
+ source: z.strictObject({ kind: z.enum(SOURCE_REF_KINDS), value: z.string().min(1).max(100) }).optional().describe("What you read to design it"),
139
+ rationale: z.string().min(1).max(400).optional().describe("Why the case is worth having")
140
+ });
141
+ var CASE_GENERATION_TITLE_MAX = 300;
142
+ var CASE_GENERATION_MAX_CASES = 12;
143
+ var CASE_GENERATION_DEFAULT_CASES = 8;
144
+ var CASE_GENERATION_MIN_WORDS = 20;
145
+ var CASE_GENERATION_TEXT_MAX = 12e3;
146
+ var caseGenerationBody = {
147
+ input: z.strictObject({
148
+ kind: z.literal("pasted-text"),
149
+ text: z.string().describe(`The requirement, story or ticket text, at least ${CASE_GENERATION_MIN_WORDS} words and at most ${CASE_GENERATION_TEXT_MAX} characters`),
150
+ title: z.string().trim().max(CASE_GENERATION_TITLE_MAX).optional()
151
+ }),
152
+ maxCases: z.number().int().min(1).max(CASE_GENERATION_MAX_CASES).optional().describe(`How many proposals at most; ${CASE_GENERATION_DEFAULT_CASES} when left out`),
153
+ language: z.string().trim().min(2).max(35).optional().describe("The cases' language; the project's AI language when left out"),
154
+ confirmDuplicates: z.boolean().optional().describe("true: go ahead although cases or proposals from this text exist (the platform answers 409 duplicate_source first)")
155
+ };
156
+ var API_METHODS = ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
157
+ var proposedEndpoint = z.strictObject({
158
+ method: z.enum(API_METHODS),
159
+ path: z.string().min(1).max(512).regex(/^\/[^?#\s]*$/, "a path template starts with / and has no query").describe("A template: /users/{id}, never /users/42"),
160
+ source: z.enum(["spec", "code", "traffic"]),
161
+ trust: z.enum(["confirmed", "derived"]).optional(),
162
+ summary: z.string().trim().min(1).max(500).optional(),
163
+ auth: z.array(z.string().trim().min(1).max(100)).max(10).optional(),
164
+ environment: z.string().trim().min(1).max(100).optional(),
165
+ seenAt: z.string().optional().describe("ISO 8601 date and time with an offset")
166
+ });
167
+ var REVIEW_STATES = ["pending", "changes_requested", "approved", "rejected"];
168
+ var REVIEW_KINDS = ["result", "proposal", "discovered", "endpoint", "strategy", "report", "memory_rule"];
169
+ var REJECTION_CATEGORIES = ["duplicate", "incorrect", "out-of-scope", "low-value", "not-testable", "other"];
170
+ var entity = z.looseObject({ id: z.string().optional() });
171
+ var plannedRequest = z.object({
172
+ method: z.string(),
173
+ path: z.string(),
174
+ query: z.record(z.string(), z.string()).optional(),
175
+ body: z.unknown().optional()
176
+ });
177
+ var writeOutput = z.object({
178
+ dryRun: z.boolean(),
179
+ request: plannedRequest.optional(),
180
+ result: entity.optional()
181
+ });
182
+ var strategyOutput = writeOutput.extend({ checked: z.boolean().optional(), findings: z.array(z.unknown()).optional() });
183
+ var batchOutput = z.object({
184
+ dryRun: z.boolean(),
185
+ requested: z.number().int(),
186
+ applied: z.number().int(),
187
+ requests: z.array(plannedRequest).optional(),
188
+ results: z.array(
189
+ z.object({
190
+ ok: z.boolean(),
191
+ status: z.number().int().optional(),
192
+ id: z.string().optional(),
193
+ error: z.string().optional(),
194
+ code: z.string().optional()
195
+ })
196
+ ).optional(),
197
+ report: z.looseObject({}).optional()
198
+ });
199
+ var bulkPreview = z.looseObject({
200
+ total: z.number().int(),
201
+ confirm: z.string(),
202
+ expiresInSeconds: z.number().int()
203
+ });
204
+
205
+ // src/mcp-testing/lint/thresholds.ts
206
+ var PLUNE_ANSWER_MEASURES = {
207
+ plune_project_context: { tokens: 387, of: "3 projects and 3 suites" },
208
+ plune_cases_search: { tokens: 7678, of: "a project of 48 cases" },
209
+ plune_review_list: { tokens: 695, of: "7 pending entries" },
210
+ plune_mission_get: { tokens: 455, of: "a mission with 5 sources" }
211
+ };
212
+ var HEADROOM = 0.1;
213
+ var limitOf = (measure) => Math.ceil(measure * (1 + HEADROOM));
214
+ var PLUNE_BUDGET = {
215
+ /** A limit is the measure times (1 + headroom), rounded up. */
216
+ headroom: HEADROOM,
217
+ /** A measure below this share of its limit means the limit is too loose: with 10% headroom a list may shrink ~12%. */
218
+ tooLooseShare: 0.8,
219
+ /** Whole tool lists, outputSchema and annotations included. */
220
+ lists: {
221
+ /** 2025 era, write scope, as listed first: 17 tools, measured 8927 on 2026-11-20 (8853 before the measured-answer lines of #2988). */
222
+ writeFirst: 9272,
223
+ /** 2025 era, write scope, after plune_discover_tools: 22 tools, measured 11403 on 2026-11-20 (11329 before the measured-answer lines). */
224
+ writeAll: 11926,
225
+ /** Read scope, either era: 7 tools, measured 2296 on 2026-11-20 (2222 before the measured-answer lines; a read token is not offered plune_discover_tools). */
226
+ read: 2445,
227
+ /** 2026-07-28 era, write scope: 17 tools, the list does not change after discover; measured 8927 on 2026-11-20 (8853 before the measured-answer lines). */
228
+ modernWrite: 9272
229
+ },
230
+ /** The biggest single tool, plune_strategy_propose, measured 2177. */
231
+ largestTool: 2395,
232
+ /**
233
+ * The text content of an answer, on live answers recorded in plune-budget.fixtures.ts, measured 2026-11-14 with the
234
+ * text unindented (before, with a two-space indent): the beta demo project of 2026-11-10 (cases in Ukrainian) gives
235
+ * plune_project_context with 3 projects, 3 suites, no missions 387 (548); plune_cases_search 7678 (10509) for the
236
+ * whole project of 48 cases (a page of 100 is not reached); plune_review_list of 7 pending entries 695 (895). The demo
237
+ * has no missions, so plune_mission_get reads a mission with 5 sources captured live on a beta test project on
238
+ * 2026-11-14: 455 (585; the synthetic mission it replaced measured 476 indented, under its limit of 524).
239
+ */
240
+ answers: {
241
+ plune_project_context: limitOf(PLUNE_ANSWER_MEASURES.plune_project_context.tokens),
242
+ plune_cases_search: limitOf(PLUNE_ANSWER_MEASURES.plune_cases_search.tokens),
243
+ plune_review_list: limitOf(PLUNE_ANSWER_MEASURES.plune_review_list.tokens),
244
+ plune_mission_get: limitOf(PLUNE_ANSWER_MEASURES.plune_mission_get.tokens)
245
+ }
246
+ };
247
+ var LINT_THRESHOLDS = {
248
+ description: {
249
+ /** Shorter than this many characters says too little for a model to choose the tool. */
250
+ minLength: 40,
251
+ /** Longer than this many characters costs every request and buries the point. */
252
+ maxLength: 1e3
253
+ },
254
+ names: {
255
+ /** The specification's length bound for a tool name. */
256
+ maxLength: 128,
257
+ /** A naming style is the server's convention when more than this share of its tools use it. */
258
+ majorityShare: 0.5
259
+ },
260
+ similarity: {
261
+ /** Word-set overlap (Jaccard) of two names, the shared server prefix left out, above which they are confusable. */
262
+ names: 0.75,
263
+ /** Word-set overlap of two descriptions above which a model cannot tell the tools apart. */
264
+ descriptions: 0.6,
265
+ /** Overlap of two descriptions above which the tools are related enough that "when not to use" matters more. */
266
+ related: 0.35,
267
+ /** Words shorter than this are left out of a description's word set. */
268
+ minWordLength: 3,
269
+ /** Decimals an overlap is reported with. */
270
+ decimals: 2,
271
+ /**
272
+ * Tools above which the rules that compare every pair (`tools-similar`, `desc-no-when-not`) do not run and say
273
+ * `could-not-run`: the work grows with the square of a count the server chooses. Measured 2026-11-10 on one
274
+ * desktop core, with no two tools alike (the slowest case: no early stop): at 1000 tools the two rules take 0.25 s
275
+ * with 60-character descriptions and 2.3 s with 1000-character ones (`description.maxLength`); at 4000 short ones,
276
+ * 4.5 s. Well above the tool lists of real servers, which hold tens to hundreds.
277
+ */
278
+ maxTools: 1e3
279
+ },
280
+ schema: {
281
+ /**
282
+ * Levels an input schema may nest (a named property, or an array's items, is one level below the node it is in)
283
+ * for the rules that read every node of it (`required-unknown-property`, `param-example-missing`); deeper, they
284
+ * say `could-not-run` for the tool. The server chooses the depth, and a node's path is as long as its depth.
285
+ * Hand-written and generated schemas nest to about 10-20 levels; 64 leaves three times that, and is the number
286
+ * the `--call` path stops copying an output schema at (counted there in JSON levels, two to a property).
287
+ * Measured 2026-11-10 on one desktop core: the two rules take 0.03 ms on a chain exactly 64 levels deep (0.09 ms
288
+ * with two siblings and an array at every level), and stop within 0.2 ms on a chain of 100 000 levels. The
289
+ * recursive walk this replaced overflowed the call stack at 10 000 levels.
290
+ */
291
+ maxDepth: 64
292
+ },
293
+ size: {
294
+ /**
295
+ * Estimated tokens of the whole visible tool list above which the list is reported: the limit of our own biggest
296
+ * list (`budget.lists.writeAll`), so a server that costs more than all of ours is told so.
297
+ */
298
+ maxListTokens: PLUNE_BUDGET.lists.writeAll,
299
+ /**
300
+ * The estimate: characters of a tool's JSON divided by this, rounded up, summed over the tools. No tokenizer, no
301
+ * network, the same number in CI on every run; a limit is a measure plus headroom, never an exact token count.
302
+ * Calibrated 2026-11-10 against a provider's token-counting endpoint on two current models (both gave the same
303
+ * counts): the estimate is low. On the same JSON (name, description, input schema: the fields a model API takes) a
304
+ * tool list costs 1.57-1.72 times the estimate, the tool-use preamble of ~320 tokens left out; the largest live
305
+ * answer (JSON with Ukrainian text) 1.84 times. The limits stay in estimated tokens; for real tokens multiply by
306
+ * ~1.7 (English JSON) to ~1.85 (Cyrillic). Table: docs/features/mcp-context-budget/budget.md.
307
+ */
308
+ charsPerToken: 4,
309
+ budget: PLUNE_BUDGET
310
+ },
311
+ call: {
312
+ /**
313
+ * Estimated tokens of one `tools/call` result (its JSON, as the client receives it) above which the answer is
314
+ * reported: the limit of our own biggest answer (`budget.answers.plune_cases_search`), as `maxListTokens` is for
315
+ * the list.
316
+ */
317
+ maxResultTokens: PLUNE_BUDGET.answers.plune_cases_search
318
+ },
319
+ language: {
320
+ /**
321
+ * A text is taken to be in a listed language when at least this many of its stop words occur; two, so a lone
322
+ * "a" or "in" of another Latin-script language does not pass for English.
323
+ */
324
+ minStopwords: 2
325
+ },
326
+ /** Name words that say a tool returns a list, so it should take a page size or cursor. */
327
+ listVerbs: ["list", "search", "find", "query", "browse"],
328
+ /** Parameter names that page a list. */
329
+ pagingParams: ["limit", "cursor", "page", "offset", "pagesize", "perpage", "per_page", "page_size", "pagetoken", "page_token"],
330
+ /** Name words of a tool that changes something; a read-only hint on such a tool contradicts its name. */
331
+ writeVerbs: ["create", "add", "update", "edit", "delete", "remove", "set", "write", "put", "patch", "insert", "replace", "send"],
332
+ /** Name words of a tool that overwrites or removes, which is not an "additive only" update. */
333
+ overwriteVerbs: ["update", "edit", "set", "replace", "delete", "remove", "overwrite", "patch", "clear", "reset", "rename", "move"],
334
+ /** Parameter name words that say the value is not free text. Booleans only by the first word (`isActive`). */
335
+ typedParamWords: {
336
+ number: ["count", "limit", "max", "min", "size", "offset", "total", "amount", "number", "port", "timeout", "retries", "quantity", "index"],
337
+ boolean: ["is", "has", "can", "should", "allow", "enable", "enabled"],
338
+ date: ["date", "time", "timestamp", "since", "until", "deadline"],
339
+ url: ["url", "uri", "href", "link", "endpoint", "website"]
340
+ },
341
+ /**
342
+ * Words by language. `script` is the alphabet the language is written in; `letters`, when given, are letters the
343
+ * language has and its neighbours in the same alphabet do not, so a Russian text is not read as Ukrainian.
344
+ * Phrases match at the start of a word, so a stem (`не використов`) covers its inflected forms.
345
+ */
346
+ languages: {
347
+ en: {
348
+ script: "Latin",
349
+ letters: "",
350
+ stopwords: ["the", "a", "an", "to", "of", "and", "or", "is", "are", "in", "for", "with", "it", "its", "as", "at", "be", "not", "can", "you", "your", "this", "that", "them", "by", "on", "from", "if", "when", "each"],
351
+ whenNot: ["do not", "don't", "instead", "rather than", "only", "not for", "avoid", "never"],
352
+ example: ["e.g.", "for example", "for instance", "such as", "example"],
353
+ closedSet: ["one of", "either"]
354
+ },
355
+ uk: {
356
+ script: "Cyrillic",
357
+ letters: "\u0456\u0457\u0454\u0491",
358
+ stopwords: ["\u0456", "\u0439", "\u0442\u0430", "\u0432", "\u0443", "\u043D\u0430", "\u0437", "\u0456\u0437", "\u0449\u043E", "\u0446\u0435", "\u0434\u043E", "\u043D\u0435", "\u0434\u043B\u044F", "\u044F\u043A", "\u0430\u0431\u043E", "\u043A\u043E\u043B\u0438", "\u0439\u043E\u0433\u043E", "\u0457\u0457", "\u0432\u0456\u0434"],
359
+ whenNot: ["\u043D\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432", "\u043D\u0435 \u0432\u0438\u043A\u043B\u0438\u043A", "\u043D\u0435 \u0437\u0430\u0441\u0442\u043E\u0441\u043E\u0432", "\u0437\u0430\u043C\u0456\u0441\u0442\u044C", "\u043B\u0438\u0448\u0435", "\u0442\u0456\u043B\u044C\u043A\u0438", "\u043D\u0435 \u0434\u043B\u044F", "\u043D\u0456\u043A\u043E\u043B\u0438"],
360
+ example: ["\u043D\u0430\u043F\u0440\u0438\u043A\u043B\u0430\u0434", "\u043D\u0430\u043F\u0440.", "\u043F\u0440\u0438\u043A\u043B\u0430\u0434", "\u0437\u043E\u043A\u0440\u0435\u043C\u0430"],
361
+ closedSet: ["\u043E\u0434\u043D\u0435 \u0437", "\u043E\u0434\u0438\u043D \u0437", "\u043E\u0434\u043D\u0430 \u0437", "\u043E\u0434\u043D\u0435 \u0456\u0437", "\u043E\u0434\u0438\u043D \u0456\u0437", "\u043E\u0434\u043D\u0430 \u0456\u0437"]
362
+ }
363
+ }
364
+ };
365
+
366
+ // src/mcp-tools/contract.ts
367
+ var MAX_VISIBLE_TOOLS = 20;
368
+ var define = (tool) => tool;
369
+ var measuredCost = (tool) => ` Measured answer: ~${PLUNE_ANSWER_MEASURES[tool].tokens} tokens (characters / 4) for ${PLUNE_ANSWER_MEASURES[tool].of}.`;
370
+ var listPage = {
371
+ limit: z2.number().int().min(1).max(BATCH_MAX).optional(),
372
+ cursor: z2.string().min(1).optional().describe("nextCursor of the previous page")
373
+ };
374
+ var missionId = id("The mission id");
375
+ var projectId = z2.string().min(1).optional().describe("The project; the one the server was started with when left out");
376
+ var PLUNE_TOOLS = [
377
+ define({
378
+ name: "plune_project_context",
379
+ title: "Project context",
380
+ description: "Start here: learn the project you are working in with one call \u2014 its projects, the suite tree, how many test cases it has, its testing missions, how much waits in the review queue, and the rules of its memory: what a person accepted for this project, to follow without asking again." + measuredCost("plune_project_context"),
381
+ input: z2.strictObject({}),
382
+ output: z2.object({
383
+ projectId: z2.string().nullable(),
384
+ projects: z2.array(entity),
385
+ suites: z2.array(entity),
386
+ cases: z2.object({ total: z2.number().int() }),
387
+ missions: z2.array(entity),
388
+ reviewQueue: z2.object({ pending: z2.number().int(), more: z2.boolean() }),
389
+ memoryRules: z2.array(z2.object({ id: z2.string(), text: z2.string() })).describe("Rules a person accepted in the review queue and has not retired; a proposed or rejected rule is never here")
390
+ }),
391
+ write: false,
392
+ visibility: "core",
393
+ endpoints: ["GET /v1/projects", "GET /v1/suites", "GET /v1/test-cases", "GET /v1/missions", "GET /v1/review-items", "GET /v1/memory/rules"]
394
+ }),
395
+ define({
396
+ name: "plune_get",
397
+ title: "Read one object",
398
+ description: "Read one test case, run or review queue entry in full when you already hold its id \u2014 steps, state, history fields and everything the platform keeps on it. Writing results or proposing cases needs no read first; an edit that replaces a list or a text (tags, steps, a mission summary) needs the current value read first.",
399
+ input: z2.strictObject({ kind: z2.enum(["test-case", "run", "review-item"]), id: id("Its id") }),
400
+ output: z2.object({ kind: z2.string(), item: entity }),
401
+ write: false,
402
+ visibility: "core",
403
+ endpoints: ["GET /v1/test-cases/:id", "GET /v1/runs/:id", "GET /v1/review-items/:id"]
404
+ }),
405
+ define({
406
+ name: "plune_cases_search",
407
+ title: "Find test cases",
408
+ description: "Find test cases of the project by filter \u2014 free text in q, suite, state, tag, priority and the other filters of the case list \u2014 one page at a time, with the total and how many match." + measuredCost("plune_cases_search"),
409
+ input: z2.strictObject({
410
+ filters: z2.record(z2.string(), z2.union([z2.string(), z2.array(z2.string())])).optional().describe('Query filters of GET /v1/test-cases: free text is the key q, and a key the list does not know is ignored, so all cases come back; a list is OR inside one key, keys are AND-ed (e.g. {"q": "card", "tag": ["smoke"]})'),
411
+ ...listPage
412
+ }),
413
+ output: z2.object({
414
+ testCases: z2.array(entity),
415
+ total: z2.number().int().optional(),
416
+ matching: z2.number().int().optional(),
417
+ nextCursor: z2.string().nullable()
418
+ }),
419
+ write: false,
420
+ visibility: "core",
421
+ endpoints: ["GET /v1/test-cases?filters"]
422
+ }),
423
+ define({
424
+ name: "plune_review_list",
425
+ title: "Read the review queue",
426
+ description: "See what waits for a decision in the review queue \u2014 proposed cases, discovered tests, endpoints, strategies, reports \u2014 narrowed by state, kind and mission, newest first, one page at a time. The mission filter needs a platform that supports it; an older one returns the whole queue." + measuredCost("plune_review_list"),
427
+ input: z2.strictObject({
428
+ state: z2.enum(REVIEW_STATES).optional(),
429
+ kinds: z2.array(z2.enum(REVIEW_KINDS)).min(1).optional().describe("Questions are read with the question tool"),
430
+ missionId: z2.string().min(1).optional().describe("Only the entries of this mission"),
431
+ ...listPage
432
+ }),
433
+ output: z2.object({ items: z2.array(entity), nextCursor: z2.string().nullable() }),
434
+ write: false,
435
+ visibility: "core",
436
+ endpoints: ["GET /v1/review-items"]
437
+ }),
438
+ define({
439
+ name: "plune_review_decide",
440
+ title: "Decide queue entries",
441
+ description: "Approve or reject up to 100 review queue entries in one decision. The first call changes nothing and returns a preview with a confirm value; repeat the same call with confirm to apply it. An entry skipped as policy_refused was refused by the review policy of the project (for example, the person who proposed it cannot approve it): do not retry it \u2014 it needs another reviewer; its detail says why.",
442
+ input: z2.strictObject({
443
+ itemIds: z2.array(z2.string().min(1)).min(1).max(BATCH_MAX).refine((a) => new Set(a).size === a.length, { message: "an id is named once" }),
444
+ verdict: z2.enum(["approved", "rejected"]),
445
+ rejectionCategory: z2.enum(REJECTION_CATEGORIES).optional().describe("Required to reject"),
446
+ note: z2.string().trim().min(1).max(2e3).optional().describe("Why \u2014 required to reject"),
447
+ confirm: z2.string().min(1).optional().describe("The confirm value of the preview")
448
+ }),
449
+ output: z2.object({
450
+ requested: z2.number().int(),
451
+ applied: z2.number().int(),
452
+ preview: bulkPreview.optional(),
453
+ report: z2.looseObject({}).optional()
454
+ }),
455
+ write: true,
456
+ visibility: "core",
457
+ endpoints: ["POST /v1/review-items/decisions"]
458
+ }),
459
+ define({
460
+ name: "plune_case_propose",
461
+ title: "Propose test cases",
462
+ description: "Propose up to 100 new test cases for a person to review: they land in the review queue as proposals and become cases only when someone approves them. Nothing is created silently.",
463
+ input: z2.strictObject({
464
+ target: z2.string().trim().min(1).max(2048).describe("What the cases test: the product address, or the mission name"),
465
+ missionId: z2.string().min(1).optional().describe("The mission these cases are for: the review queue can then be read by it"),
466
+ cases: z2.array(proposedCase).min(1).max(BATCH_MAX),
467
+ dry_run: dryRun
468
+ }),
469
+ output: batchOutput.extend({ itemIds: z2.array(z2.string()).optional().describe("The ids of the review-queue entries created, when the platform names them") }),
470
+ write: true,
471
+ visibility: "core",
472
+ endpoints: ["POST /v1/ingest/cairn"]
473
+ }),
474
+ define({
475
+ name: "plune_cases_generate",
476
+ title: "Generate cases from pasted text",
477
+ description: "Generate test case proposals from pasted text \u2014 a requirement, a user story, the text of a ticket \u2014 with the project's AI. It spends the project's AI budget. The proposals land in the review queue and nothing becomes a case until a person approves it. The run is queued: keep its id and poll it with plune_cases_generation_get until it is done. A Jira ticket by its key is not taken here: paste its text.",
478
+ input: z2.strictObject({ projectId, ...caseGenerationBody, dry_run: dryRun }),
479
+ output: writeOutput,
480
+ write: true,
481
+ visibility: "core",
482
+ endpoints: ["POST /v1/projects/:id/case-generations"]
483
+ }),
484
+ define({
485
+ name: "plune_cases_generation_get",
486
+ title: "Read a case generation",
487
+ description: "Check where a run of cases from pasted text stands \u2014 queued, running, done, failed or cancelled \u2014 with how many proposals it made, how many it skipped, and what it cost.",
488
+ input: z2.strictObject({ projectId, generationId: id("The id the start answered with") }),
489
+ output: z2.object({ generation: entity }),
490
+ write: false,
491
+ visibility: "core",
492
+ endpoints: ["GET /v1/projects/:id/case-generations/:generationId"]
493
+ }),
494
+ define({
495
+ name: "plune_mission_create",
496
+ title: "Create a mission",
497
+ description: "Create a testing mission for a product the user has named: its name, a short description of what the product is, where it runs, and whether documentation exists. It starts as a draft. Do not guess a mission from an unclear request, not even as a placeholder draft: when the user has not said which product, ask with plune_question_ask first.",
498
+ input: z2.strictObject({ ...missionFields, dry_run: dryRun }),
499
+ output: writeOutput,
500
+ write: true,
501
+ visibility: "core",
502
+ endpoints: ["POST /v1/missions"]
503
+ }),
504
+ define({
505
+ name: "plune_mission_get",
506
+ title: "Read a mission",
507
+ description: "Read a testing mission with everything it holds \u2014 its brief, state, documentation answer and every source attached to it \u2014 before planning or continuing the work on it." + measuredCost("plune_mission_get"),
508
+ input: z2.strictObject({ missionId }),
509
+ output: z2.object({ mission: entity }),
510
+ write: false,
511
+ visibility: "core",
512
+ endpoints: ["GET /v1/missions/:id"]
513
+ }),
514
+ define({
515
+ name: "plune_mission_update",
516
+ title: "Update a mission",
517
+ description: "Change a testing mission: rename it, rewrite the brief, set or remove the address, answer whether documentation exists, or move it between draft, active and done.",
518
+ input: z2.strictObject({
519
+ missionId,
520
+ name: missionFields.name.optional(),
521
+ summary: missionFields.summary,
522
+ url: missionFields.url,
523
+ state: missionFields.state,
524
+ documentation: missionFields.documentation,
525
+ dry_run: dryRun
526
+ }).refine((b) => ["name", "summary", "url", "state", "documentation"].some((k) => b[k] !== void 0), {
527
+ message: "nothing to change"
528
+ }),
529
+ output: writeOutput,
530
+ write: true,
531
+ visibility: "core",
532
+ endpoints: ["PATCH /v1/missions/:id"]
533
+ }),
534
+ define({
535
+ name: "plune_source_add",
536
+ title: "Add a source to a mission",
537
+ description: "Attach something to read to a mission: a link (page, OpenAPI document, repository, ticket) or the text of a file of the project \u2014 Markdown, plain text or JSON, up to 1 MiB.",
538
+ input: z2.strictObject({
539
+ missionId,
540
+ kind: z2.enum([...MISSION_LINK_KINDS, "file"]),
541
+ ref: z2.string().optional().describe("The link, for url, openapi, repo and ticket"),
542
+ name: z2.string().optional().describe("The file name, for file (.md, .markdown, .txt, .json)"),
543
+ text: z2.string().optional().describe("The file text, for file"),
544
+ title: z2.string().optional(),
545
+ version: z2.string().optional(),
546
+ dry_run: dryRun
547
+ }).superRefine((b, ctx) => {
548
+ if (b.kind === "file" && (b.name === void 0 || b.text === void 0))
549
+ ctx.addIssue({ code: "custom", message: "a file source carries name and text" });
550
+ if (b.kind !== "file" && b.ref === void 0) ctx.addIssue({ code: "custom", message: "a link source carries ref" });
551
+ }),
552
+ output: writeOutput,
553
+ write: true,
554
+ visibility: "core",
555
+ endpoints: ["POST /v1/missions/:id/sources", "POST /v1/missions/:id/files"]
556
+ }),
557
+ define({
558
+ name: "plune_question_ask",
559
+ title: "Ask a person",
560
+ description: "Ask a person what you do not know instead of guessing. When the request leaves the target or scope unclear (which product, which cases), call this first, before any write, rather than only asking in your reply: it needs no mission, waits in the review queue, and its answer is read with plune_question_list. A plain question takes up to three options; an access question asks for an API description, the code, staging or a HAR file.",
561
+ input: questionInput.superRefine((b, ctx) => {
562
+ if (b.template === "plain" && b.access !== void 0) ctx.addIssue({ code: "custom", message: "access belongs to an access question" });
563
+ if (b.template === "access" && b.options !== void 0) ctx.addIssue({ code: "custom", message: "options belong to a plain question" });
564
+ if (b.template === "access" && b.access === void 0) ctx.addIssue({ code: "custom", message: "an access question names the access" });
565
+ }),
566
+ output: writeOutput,
567
+ write: true,
568
+ visibility: "core",
569
+ endpoints: ["POST /v1/review-items/questions"]
570
+ }),
571
+ define({
572
+ name: "plune_question_list",
573
+ title: "Read questions and answers",
574
+ description: "Check the questions asked to people and the answers they gave \u2014 all of them or one mission's, waiting or answered \u2014 so the work continues from what a person actually said.",
575
+ input: z2.strictObject({ missionId: z2.string().min(1).optional(), state: z2.enum(REVIEW_STATES).optional(), ...listPage }),
576
+ output: z2.object({ questions: z2.array(entity), nextCursor: z2.string().nullable() }),
577
+ write: false,
578
+ visibility: "core",
579
+ endpoints: ["GET /v1/review-items?kind=question"]
580
+ }),
581
+ define({
582
+ name: "plune_strategy_propose",
583
+ title: "Propose a test strategy",
584
+ description: "Propose a test strategy for a mission in ISTQB sections \u2014 objectives, scope in and out, approach, levels and techniques, risks, entry and exit criteria \u2014 for a person to accept.",
585
+ input: z2.strictObject({ missionId, content: strategyContent, dry_run: dryRun }),
586
+ output: strategyOutput,
587
+ write: true,
588
+ visibility: "core",
589
+ endpoints: ["POST /v1/missions/:id/strategy"]
590
+ }),
591
+ define({
592
+ name: "plune_report_request",
593
+ title: "Request the mission report",
594
+ description: "Ask the platform to build the completion report of a mission from its own data and queue it for a person to approve; it needs an accepted strategy first.",
595
+ input: z2.strictObject({ missionId, dry_run: dryRun }),
596
+ output: writeOutput,
597
+ write: true,
598
+ visibility: "core",
599
+ endpoints: ["POST /v1/missions/:id/report"]
600
+ }),
601
+ define({
602
+ name: "plune_discover_tools",
603
+ title: "Find more tools",
604
+ description: "Look for a capability that is not in your tool list \u2014 editing cases (plune_cases_update), writing results into a run (plune_results_write), starting runs (plune_run_create), cataloguing API endpoints (plune_endpoint_propose), a raw API call (plune_api_request) \u2014 and switch the ones you need on for this session by name, in one call. A tool switched on can be called from the next step, and its description in this answer says what it needs. Writing results needs no read of the run first; editing a case replaces its title, tags and steps whole, so read the case before changing them.",
605
+ input: z2.strictObject({
606
+ query: z2.string().trim().min(1).max(200).optional().describe('Two or three words of the task, e.g. "write results": a tool is listed only when every word is in its name, title or description'),
607
+ names: z2.array(z2.string().min(1)).min(1).max(MAX_VISIBLE_TOOLS).optional().describe("Tools to switch on")
608
+ }),
609
+ output: z2.object({
610
+ revealed: z2.array(z2.string()),
611
+ available: z2.array(
612
+ z2.object({
613
+ name: z2.string(),
614
+ title: z2.string(),
615
+ description: z2.string(),
616
+ write: z2.boolean(),
617
+ inputSchema: z2.record(z2.string(), z2.unknown()).optional().describe("JSON Schema of the arguments, where the tool list is fixed and a tool is called by its name")
618
+ })
619
+ ),
620
+ visible: z2.array(z2.string())
621
+ }),
622
+ write: false,
623
+ visibility: "core",
624
+ endpoints: ["LOCAL /discover"]
625
+ }),
626
+ define({
627
+ name: "plune_cases_update",
628
+ title: "Edit test cases",
629
+ description: "Edit up to 100 existing test cases in one call \u2014 title, steps, expected result, priority, tags, suite \u2014 each applied on its own, with a count of how many were applied.",
630
+ input: z2.strictObject({
631
+ cases: z2.array(z2.strictObject({ id: id("The case id"), changes: z2.record(z2.string(), z2.unknown()).describe("Fields of PATCH /v1/test-cases/:id") })).min(1).max(BATCH_MAX),
632
+ dry_run: dryRun
633
+ }),
634
+ output: batchOutput,
635
+ write: true,
636
+ visibility: "discoverable",
637
+ endpoints: ["PATCH /v1/test-cases/:id"]
638
+ }),
639
+ define({
640
+ name: "plune_run_create",
641
+ title: "Start a run",
642
+ description: "Start a test run on the platform to record results into \u2014 named, with its environment and the cases it covers \u2014 using the body of POST /v1/runs (schemaVersion 2).",
643
+ input: z2.strictObject({ run: z2.record(z2.string(), z2.unknown()).describe("The body of POST /v1/runs"), dry_run: dryRun }),
644
+ output: writeOutput,
645
+ write: true,
646
+ visibility: "discoverable",
647
+ endpoints: ["POST /v1/runs"]
648
+ }),
649
+ define({
650
+ name: "plune_results_write",
651
+ title: "Write results into a run",
652
+ description: "Record up to 100 test results into an open run in one request \u2014 passed, failed, skipped, with their keys and evidence \u2014 and learn how many the platform accepted. The run id is enough: the run need not be read first. Each result names its case by testCaseId, found with plune_cases_search; when no case matches a name, ask the person instead of searching on.",
653
+ input: z2.strictObject({
654
+ runId: id("The run id"),
655
+ results: z2.array(z2.record(z2.string(), z2.unknown())).min(1).max(BATCH_MAX).describe("Results as POST /v1/runs/:id/results takes them: each with testCaseId, a resultKey of your own and a status"),
656
+ combination: z2.number().int().min(0).optional(),
657
+ configuration: z2.record(z2.string(), z2.string()).optional(),
658
+ dry_run: dryRun
659
+ }),
660
+ output: batchOutput,
661
+ write: true,
662
+ visibility: "discoverable",
663
+ endpoints: ["POST /v1/runs/:id/results"]
664
+ }),
665
+ define({
666
+ name: "plune_endpoint_propose",
667
+ title: "Propose API endpoints",
668
+ description: "Propose up to 100 API endpoints you found in a spec, the code or traffic for the project's API catalog; each waits in the review queue until a person approves it.",
669
+ input: z2.strictObject({ endpoints: z2.array(proposedEndpoint).min(1).max(BATCH_MAX), dry_run: dryRun }),
670
+ output: batchOutput,
671
+ write: true,
672
+ visibility: "discoverable",
673
+ endpoints: ["POST /v1/review-items/endpoints"]
674
+ }),
675
+ define({
676
+ name: "plune_api_request",
677
+ title: "Call the REST API directly",
678
+ description: "Reach any Plune REST endpoint under /v1 that no other tool covers. Every guard still holds: a deletion is previewed first and needs confirm, and the platform refuses an agent what it refuses over HTTP.",
679
+ input: z2.strictObject({
680
+ method: z2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
681
+ path: z2.string().min(1).max(2048).describe("A path under /v1, e.g. /v1/suites"),
682
+ query: z2.record(z2.string(), z2.string()).optional(),
683
+ body: z2.unknown().optional(),
684
+ confirm: z2.string().min(1).optional().describe("The confirm value of a preview"),
685
+ dry_run: dryRun
686
+ }),
687
+ output: z2.object({
688
+ status: z2.number().int().optional(),
689
+ body: z2.unknown().optional(),
690
+ dryRun: z2.boolean().optional(),
691
+ request: plannedRequest.optional(),
692
+ preview: z2.looseObject({ method: z2.string(), path: z2.string(), confirm: z2.string(), expiresInSeconds: z2.number().int() }).optional()
693
+ }),
694
+ write: true,
695
+ visibility: "discoverable",
696
+ endpoints: ["ANY /v1/*"]
697
+ })
698
+ ];
699
+ var PLUNE_TOOL_NAMES = PLUNE_TOOLS.map((t) => t.name);
700
+ var BY_NAME = new Map(PLUNE_TOOLS.map((t) => [t.name, t]));
701
+ function pluneTool(name) {
702
+ const tool = BY_NAME.get(name);
703
+ if (tool === void 0) throw new Error(`unknown tool: ${name}`);
704
+ return tool;
705
+ }
706
+ function isPluneToolName(name) {
707
+ return BY_NAME.has(name);
708
+ }
709
+ function offeredTo(tool, scope) {
710
+ if (scope !== "read") return true;
711
+ if (tool.write) return false;
712
+ return tool.name !== "plune_discover_tools" || PLUNE_TOOLS.some((t) => t.visibility !== "core" && !t.write);
713
+ }
714
+ function defaultVisibleTools(scope) {
715
+ return PLUNE_TOOLS.filter((t) => t.visibility === "core" && offeredTo(t, scope)).map((t) => t.name);
716
+ }
717
+
718
+ // src/mcp-tools/execute.ts
719
+ import { createHash, randomBytes, randomUUID } from "crypto";
720
+ import { z as z3 } from "zod";
721
+
722
+ // src/mcp-tools/client.ts
723
+ var PluneApiError = class extends Error {
724
+ constructor(status, body) {
725
+ const error = bodyField(body, "error");
726
+ super(error ?? `HTTP ${status}`);
727
+ this.status = status;
728
+ this.body = body;
729
+ this.name = "PluneApiError";
730
+ }
731
+ status;
732
+ body;
733
+ get code() {
734
+ return bodyField(this.body, "code");
735
+ }
736
+ };
737
+ var PluneNetworkError = class extends Error {
738
+ constructor(apiUrl) {
739
+ super(`could not reach Plune at ${apiUrl}`);
740
+ this.apiUrl = apiUrl;
741
+ this.name = "PluneNetworkError";
742
+ }
743
+ apiUrl;
744
+ };
745
+ function bodyField(body, key) {
746
+ if (body === null || typeof body !== "object") return void 0;
747
+ const value = body[key];
748
+ return typeof value === "string" ? value : void 0;
749
+ }
750
+ function apiBase(apiUrl) {
751
+ return apiUrl.replace(/\/+$/, "");
752
+ }
753
+ function buildUrl(apiUrl, req) {
754
+ const url = new URL(apiBase(apiUrl) + req.path);
755
+ for (const [key, value] of Object.entries(req.query ?? {})) {
756
+ for (const v of typeof value === "string" ? [value] : value) url.searchParams.append(key, v);
757
+ }
758
+ return url;
759
+ }
760
+ function createPluneApi(opts) {
761
+ const doFetch = opts.fetchImpl ?? fetch;
762
+ const headers = {
763
+ authorization: `Bearer ${opts.token}`,
764
+ accept: "application/json",
765
+ "x-plune-session": opts.sessionId,
766
+ ...opts.projectId === void 0 ? {} : { "x-plune-project": opts.projectId },
767
+ ...opts.userAgent === void 0 ? {} : { "user-agent": opts.userAgent }
768
+ };
769
+ return async function request(req) {
770
+ const url = buildUrl(opts.apiUrl, req);
771
+ let res;
772
+ try {
773
+ res = await doFetch(url.toString(), {
774
+ method: req.method,
775
+ headers: req.body === void 0 ? headers : { ...headers, "content-type": "application/json" },
776
+ ...req.body === void 0 ? {} : { body: JSON.stringify(req.body) },
777
+ // Host pinning: a redirect elsewhere would carry the token there.
778
+ redirect: "manual"
779
+ });
780
+ } catch {
781
+ throw new PluneNetworkError(apiBase(opts.apiUrl));
782
+ }
783
+ const text = await res.text();
784
+ let body = text;
785
+ if (text !== "") {
786
+ try {
787
+ body = JSON.parse(text);
788
+ } catch {
789
+ }
790
+ } else {
791
+ body = void 0;
792
+ }
793
+ if (res.status < 200 || res.status >= 300) throw new PluneApiError(res.status, body);
794
+ return { status: res.status, body };
795
+ };
796
+ }
797
+
798
+ // src/mcp-tools/execute.ts
799
+ var CONFIRM_TTL_MS = 5 * 60 * 1e3;
800
+ var READ_ONLY_REFUSAL = "read-only token";
801
+ var NO_PROJECT = "projectId is needed: the server was started without a project (--project or PLUNE_PROJECT). plune_project_context lists the projects.";
802
+ var readScopeMessage = (what) => `This token has the read scope, so ${what}. Use a token with the write scope (Plune \u2192 Account \u2192 API tokens) and restart the server.`;
803
+ var fail = (code, message, extra = {}) => ({
804
+ ok: false,
805
+ error: { code, message, ...extra }
806
+ });
807
+ function detailLines(body) {
808
+ const b = asRecord(body);
809
+ const lines = [...asArray(b["findings"]), ...asArray(b["details"])].map((d) => {
810
+ if (typeof d === "string") return `- ${d}`;
811
+ const f = asRecord(d);
812
+ const where = [f["rule"], f["path"]].filter((x) => typeof x === "string").join(" at ");
813
+ const said = typeof f["message"] === "string" ? f["message"] : where === "" ? JSON.stringify(d) : "";
814
+ return `- ${[where, said].filter(Boolean).join(": ")}`;
815
+ });
816
+ return lines.length === 0 ? "" : "\n" + lines.join("\n");
817
+ }
818
+ function errorOf(err) {
819
+ if (err instanceof PluneApiError) {
820
+ if (err.status === 401)
821
+ return { status: 401, code: "token_rejected", message: `Plune rejected the token (401): ${err.message}. Run \`plune login\` or set PLUNE_TOKEN to a live token.` };
822
+ if (err.status === 403 && err.message === READ_ONLY_REFUSAL)
823
+ return { status: 403, code: "read_only_token", message: `Plune refused (403): ${readScopeMessage("it cannot write")}` };
824
+ const quota = err.status === 429 && asRecord(err.body)["quota"] !== void 0;
825
+ const code = err.code ?? (quota ? "quota_exceeded" : `http_${err.status}`);
826
+ const why = quota ? "a plan limit is reached, not a missing permission \u2014 " : err.status === 403 ? "the token or its user lacks the permission, not a plan limit \u2014 " : "";
827
+ return { status: err.status, code, message: `Plune refused (${err.status} ${code}): ${why}${err.message}${detailLines(err.body)}`, details: err.body };
828
+ }
829
+ if (err instanceof PluneNetworkError) return { code: "network", message: `${err.message}. Check PLUNE_API_URL and the network.` };
830
+ throw err;
831
+ }
832
+ var zodMessage = (error) => error.issues.map((i) => `${i.path.join(".") || "(input)"}: ${i.message}`).join("; ");
833
+ var path = (template, ...ids) => {
834
+ let i = 0;
835
+ return template.replace(/:[a-z]+/gi, () => encodeURIComponent(ids[i++] ?? ""));
836
+ };
837
+ var withoutUndefined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
838
+ var asRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
839
+ var asArray = (v) => Array.isArray(v) ? v : [];
840
+ var cursorOf = (v) => typeof v === "string" ? v : null;
841
+ function isDeletion(req) {
842
+ if (req.method === "DELETE") return true;
843
+ if (asRecord(asRecord(req.body)["action"])["kind"] === "delete") return true;
844
+ return /\/(bulk-delete|purge|empty)$/.test(req.path);
845
+ }
846
+ var rawWrites = (method, p) => method !== "GET" && !(method === "POST" && p === "/v1/test-cases/resolve");
847
+ function safePath(apiUrl, raw) {
848
+ if (!/^\/v1\/[^\\\s]*$/.test(raw) || raw.startsWith("//") || raw.includes("?") || raw.includes("#")) return void 0;
849
+ if (raw.split("/").some((s) => s === "." || s === ".." || /^%2e/i.test(s))) return void 0;
850
+ const base = new URL(apiUrl);
851
+ const url = new URL(raw, base);
852
+ return url.origin === base.origin && url.pathname.startsWith("/v1/") ? raw : void 0;
853
+ }
854
+ function createPluneToolExecutor(opts) {
855
+ const sessionId = opts.sessionId ?? randomUUID();
856
+ const now = opts.now ?? Date.now;
857
+ const request = createPluneApi({ ...opts, sessionId });
858
+ let scope = opts.scope;
859
+ const revealed = /* @__PURE__ */ new Set();
860
+ const confirms = /* @__PURE__ */ new Map();
861
+ const visibleTools = () => {
862
+ const core = defaultVisibleTools(scope);
863
+ const extra = [...revealed].filter((n) => !(scope === "read" && pluneTool(n).write) && !core.includes(n));
864
+ return [...core, ...extra];
865
+ };
866
+ async function call(req) {
867
+ try {
868
+ return await request(req);
869
+ } catch (err) {
870
+ if (err instanceof PluneApiError && err.status === 403 && err.message === READ_ONLY_REFUSAL) scope = "read";
871
+ throw err;
872
+ }
873
+ }
874
+ const planned = (req) => withoutUndefined({ method: req.method, path: req.path, query: req.query, body: req.body });
875
+ async function write(req, dry) {
876
+ if (dry === true) return { dryRun: true, request: planned(req) };
877
+ const res = await call(req);
878
+ return { dryRun: false, result: asRecord(res.body) };
879
+ }
880
+ async function batch(reqs, dry, idOf) {
881
+ if (dry === true) return { dryRun: true, requested: reqs.length, applied: 0, requests: reqs.map(planned) };
882
+ const results = [];
883
+ for (const [i, req] of reqs.entries()) {
884
+ try {
885
+ const res = await call(req);
886
+ results.push(withoutUndefined({ ok: true, status: res.status, id: idOf(res.body, i) }));
887
+ } catch (err) {
888
+ const e = errorOf(err);
889
+ if (e.code === "token_rejected" || e.code === "read_only_token" || e.code === "network") throw err;
890
+ results.push(withoutUndefined({ ok: false, status: e.status, error: e.message, code: e.code }));
891
+ }
892
+ }
893
+ return { dryRun: false, requested: reqs.length, applied: results.filter((r) => r["ok"] === true).length, results };
894
+ }
895
+ const fingerprint = (req) => JSON.stringify([req.method, req.path, req.query ?? {}, req.body ?? null]);
896
+ const str = (v) => v;
897
+ const handlers = {
898
+ async plune_project_context() {
899
+ const [projects, suites, cases, missions, queue, memory] = await Promise.all([
900
+ call({ method: "GET", path: "/v1/projects" }),
901
+ call({ method: "GET", path: "/v1/suites" }),
902
+ call({ method: "GET", path: "/v1/test-cases", query: { limit: "1", stability: "0" } }),
903
+ call({ method: "GET", path: "/v1/missions" }),
904
+ call({ method: "GET", path: "/v1/review-items", query: { state: "pending", limit: "100" } }),
905
+ // A platform that keeps no project memory yet answers 404: no rules, and the rest of the context still stands.
906
+ call({ method: "GET", path: "/v1/memory/rules", query: { state: "in_force" } }).catch((err) => {
907
+ if (err instanceof PluneApiError && err.status === 404) return { status: 404, body: { rules: [] } };
908
+ throw err;
909
+ })
910
+ ]);
911
+ const memoryRules = asArray(asRecord(memory.body)["rules"]).map(asRecord).filter((r) => r["inForce"] === true && typeof r["id"] === "string" && typeof r["text"] === "string").map((r) => ({ id: str(r["id"]), text: str(r["text"]) }));
912
+ const projectList = asArray(asRecord(projects.body)["projects"]);
913
+ const only = projectList.length === 1 ? asRecord(projectList[0])["id"] : void 0;
914
+ const projectId2 = opts.projectId ?? (typeof only === "string" ? only : null);
915
+ const total = asRecord(cases.body)["total"];
916
+ return {
917
+ projectId: projectId2,
918
+ projects: projectList,
919
+ suites: asArray(asRecord(suites.body)["suites"]),
920
+ cases: { total: typeof total === "number" ? total : 0 },
921
+ missions: asArray(asRecord(missions.body)["missions"]),
922
+ reviewQueue: { pending: asArray(asRecord(queue.body)["items"]).length, more: cursorOf(asRecord(queue.body)["nextCursor"]) !== null },
923
+ memoryRules
924
+ };
925
+ },
926
+ async plune_get(i) {
927
+ const route = { "test-case": "/v1/test-cases/:id", run: "/v1/runs/:id", "review-item": "/v1/review-items/:id" }[str(i["kind"])];
928
+ const res = await call({ method: "GET", path: path(route, str(i["id"])) });
929
+ return { kind: str(i["kind"]), item: asRecord(res.body) };
930
+ },
931
+ async plune_cases_search(i) {
932
+ const query = withoutUndefined({
933
+ ...i["filters"],
934
+ // A full case weighs ~160 estimated tokens, so the platform's own page of up to 200 filled a model's context
935
+ // in one answer; 20 a page, the rest a cursor away, unless the caller asks for more.
936
+ limit: String(i["limit"] ?? 20),
937
+ cursor: i["cursor"],
938
+ stability: "0"
939
+ });
940
+ const body = asRecord((await call({ method: "GET", path: "/v1/test-cases", query })).body);
941
+ return withoutUndefined({
942
+ testCases: asArray(body["testCases"]),
943
+ total: typeof body["total"] === "number" ? body["total"] : void 0,
944
+ matching: typeof body["matching"] === "number" ? body["matching"] : void 0,
945
+ nextCursor: cursorOf(body["nextCursor"])
946
+ });
947
+ },
948
+ async plune_review_list(i) {
949
+ const kinds = i["kinds"];
950
+ const query = withoutUndefined({
951
+ state: i["state"],
952
+ kind: kinds?.join(","),
953
+ missionId: i["missionId"],
954
+ limit: i["limit"] === void 0 ? void 0 : String(i["limit"]),
955
+ cursor: i["cursor"]
956
+ });
957
+ const body = asRecord((await call({ method: "GET", path: "/v1/review-items", query })).body);
958
+ return { items: asArray(body["items"]), nextCursor: cursorOf(body["nextCursor"]) };
959
+ },
960
+ async plune_review_decide(i) {
961
+ const itemIds = i["itemIds"];
962
+ const res = await call({
963
+ method: "POST",
964
+ path: "/v1/review-items/decisions",
965
+ ...i["confirm"] === void 0 ? {} : { query: { confirm: str(i["confirm"]) } },
966
+ body: withoutUndefined({ itemIds, state: i["verdict"], rejectionCategory: i["rejectionCategory"], note: i["note"] })
967
+ });
968
+ const body = asRecord(res.body);
969
+ if (body["preview"] !== void 0) return { requested: itemIds.length, applied: 0, preview: asRecord(body["preview"]) };
970
+ const applied = body["applied"];
971
+ return { requested: itemIds.length, applied: typeof applied === "number" ? applied : 0, report: body };
972
+ },
973
+ async plune_case_propose(i) {
974
+ const cases = i["cases"].map((c) => {
975
+ const steps = c["steps"];
976
+ const stableId = createHash("sha256").update([c["title"], ...steps, c["expected"]].join("\n")).digest("hex").slice(0, 32);
977
+ return withoutUndefined({ stableId, execution: "manual", ...c });
978
+ });
979
+ const req = {
980
+ method: "POST",
981
+ path: "/v1/ingest/cairn",
982
+ body: {
983
+ schemaVersion: 1,
984
+ run: withoutUndefined({ runId: `mcp-${sessionId}-${randomUUID().slice(0, 8)}`, mode: "design", target: str(i["target"]), missionId: i["missionId"] }),
985
+ cases
986
+ }
987
+ };
988
+ if (i["dry_run"] === true) return { dryRun: true, requested: cases.length, applied: 0, requests: [planned(req)] };
989
+ const summary = asRecord((await call(req)).body);
990
+ const proposed = summary["proposed"];
991
+ const ids = asArray(summary["itemIds"]).filter((x) => typeof x === "string");
992
+ return { dryRun: false, requested: cases.length, applied: typeof proposed === "number" ? proposed : 0, ...ids.length > 0 ? { itemIds: ids } : {}, report: summary };
993
+ },
994
+ async plune_cases_generate(i) {
995
+ const { dry_run, projectId: projectId2, ...body } = i;
996
+ const project = projectId2 ?? opts.projectId;
997
+ if (project === void 0) return fail("invalid_input", NO_PROJECT);
998
+ return write({ method: "POST", path: path("/v1/projects/:id/case-generations", project), body: withoutUndefined(body) }, dry_run);
999
+ },
1000
+ async plune_cases_generation_get(i) {
1001
+ const project = i["projectId"] ?? opts.projectId;
1002
+ if (project === void 0) return fail("invalid_input", NO_PROJECT);
1003
+ const res = await call({ method: "GET", path: path("/v1/projects/:id/case-generations/:generationId", project, str(i["generationId"])) });
1004
+ return { generation: asRecord(res.body) };
1005
+ },
1006
+ async plune_mission_create(i) {
1007
+ const { dry_run, ...body } = i;
1008
+ return write({ method: "POST", path: "/v1/missions", body: withoutUndefined(body) }, dry_run);
1009
+ },
1010
+ async plune_mission_get(i) {
1011
+ const res = await call({ method: "GET", path: path("/v1/missions/:id", str(i["missionId"])) });
1012
+ return { mission: asRecord(res.body) };
1013
+ },
1014
+ async plune_mission_update(i) {
1015
+ const { dry_run, missionId: missionId2, ...body } = i;
1016
+ return write({ method: "PATCH", path: path("/v1/missions/:id", str(missionId2)), body: withoutUndefined(body) }, dry_run);
1017
+ },
1018
+ async plune_source_add(i) {
1019
+ const parsed = (i["kind"] === "file" ? fileSource : linkSource).safeParse(withoutUndefined(i));
1020
+ if (!parsed.success) return fail("invalid_input", `The input does not fit: ${zodMessage(parsed.error)}`);
1021
+ const { dry_run, missionId: missionId2, kind, ...rest } = parsed.data;
1022
+ const req = kind === "file" ? { method: "POST", path: path("/v1/missions/:id/files", str(missionId2)), body: withoutUndefined(rest) } : { method: "POST", path: path("/v1/missions/:id/sources", str(missionId2)), body: withoutUndefined({ kind, ...rest }) };
1023
+ return write(req, dry_run);
1024
+ },
1025
+ async plune_question_ask(i) {
1026
+ const { dry_run, ...body } = i;
1027
+ return write({ method: "POST", path: "/v1/review-items/questions", body: withoutUndefined(body) }, dry_run);
1028
+ },
1029
+ async plune_question_list(i) {
1030
+ const query = withoutUndefined({
1031
+ kind: "question",
1032
+ state: i["state"],
1033
+ limit: i["limit"] === void 0 ? void 0 : String(i["limit"]),
1034
+ cursor: i["cursor"]
1035
+ });
1036
+ const body = asRecord((await call({ method: "GET", path: "/v1/review-items", query })).body);
1037
+ const missionId2 = i["missionId"];
1038
+ const questions = asArray(body["items"]).filter(
1039
+ (item) => missionId2 === void 0 || asRecord(asRecord(item)["question"])["missionId"] === missionId2
1040
+ );
1041
+ return { questions, nextCursor: cursorOf(body["nextCursor"]) };
1042
+ },
1043
+ async plune_strategy_propose(i) {
1044
+ const req = { method: "POST", path: path("/v1/missions/:id/strategy", str(i["missionId"])), body: i["content"] };
1045
+ if (i["dry_run"] === true) {
1046
+ try {
1047
+ const res = await call({ ...req, path: `${req.path}/check` });
1048
+ return { dryRun: true, checked: true, findings: asArray(asRecord(res.body)["findings"]), request: planned(req) };
1049
+ } catch (err) {
1050
+ if (!(err instanceof PluneApiError && (err.status === 404 && err.code !== "mission_not_found" || err.status === 403 && err.message === READ_ONLY_REFUSAL))) throw err;
1051
+ return { dryRun: true, checked: false, request: planned(req) };
1052
+ }
1053
+ }
1054
+ return write({ method: "POST", path: path("/v1/missions/:id/strategy", str(i["missionId"])), body: i["content"] }, i["dry_run"]);
1055
+ },
1056
+ async plune_report_request(i) {
1057
+ return write({ method: "POST", path: path("/v1/missions/:id/report", str(i["missionId"])), body: {} }, i["dry_run"]);
1058
+ },
1059
+ async plune_discover_tools(i) {
1060
+ const names = i["names"] ?? [];
1061
+ const unknown = names.filter((n) => !isPluneToolName(n));
1062
+ if (unknown.length > 0) return fail("invalid_input", `No such tool: ${unknown.join(", ")}. Call this tool without names to see what there is.`);
1063
+ const refused = names.filter((n) => scope === "read" && pluneTool(n).write);
1064
+ if (refused.length > 0) return fail("read_only_token", readScopeMessage(`${refused.join(", ")} cannot be switched on`));
1065
+ const fixed = opts.fixedToolList === true;
1066
+ if (!fixed) for (const n of names) revealed.add(n);
1067
+ const words = (i["query"] ?? "").toLowerCase().split(/\s+/).filter(Boolean);
1068
+ const visible = visibleTools();
1069
+ const available = PLUNE_TOOLS.filter((t) => !visible.includes(t.name) && !(scope === "read" && t.write)).filter((t) => words.every((w) => `${t.name} ${t.title} ${t.description}`.toLowerCase().includes(w))).map((t) => ({
1070
+ name: t.name,
1071
+ title: t.title,
1072
+ description: t.description,
1073
+ write: t.write,
1074
+ ...fixed ? { inputSchema: z3.toJSONSchema(t.input, { target: "draft-2020-12", io: "input" }) } : {}
1075
+ }));
1076
+ return { revealed: fixed ? [] : names, available, visible };
1077
+ },
1078
+ async plune_cases_update(i) {
1079
+ const cases = i["cases"];
1080
+ return batch(
1081
+ cases.map((c) => ({ method: "PATCH", path: path("/v1/test-cases/:id", c.id), body: c.changes })),
1082
+ i["dry_run"],
1083
+ (_b, n) => cases[n]?.id
1084
+ );
1085
+ },
1086
+ async plune_run_create(i) {
1087
+ return write({ method: "POST", path: "/v1/runs", body: i["run"] }, i["dry_run"]);
1088
+ },
1089
+ async plune_results_write(i) {
1090
+ const results = i["results"];
1091
+ const req = {
1092
+ method: "POST",
1093
+ path: path("/v1/runs/:id/results", str(i["runId"])),
1094
+ body: withoutUndefined({ results, combination: i["combination"], configuration: i["configuration"] })
1095
+ };
1096
+ if (i["dry_run"] === true) return { dryRun: true, requested: results.length, applied: 0, requests: [planned(req)] };
1097
+ const report = asRecord((await call(req)).body);
1098
+ const accepted = asRecord(report["counts"])["accepted"];
1099
+ return { dryRun: false, requested: results.length, applied: typeof accepted === "number" ? accepted : 0, report };
1100
+ },
1101
+ async plune_endpoint_propose(i) {
1102
+ return batch(
1103
+ i["endpoints"].map((e) => ({ method: "POST", path: "/v1/review-items/endpoints", body: withoutUndefined(e) })),
1104
+ i["dry_run"],
1105
+ (b) => asRecord(b)["id"]
1106
+ );
1107
+ },
1108
+ async plune_api_request(i) {
1109
+ const method = str(i["method"]);
1110
+ const p = safePath(opts.apiUrl, str(i["path"]));
1111
+ if (p === void 0) return fail("invalid_input", `path must be a path under /v1 on ${new URL(opts.apiUrl).origin}, e.g. /v1/suites \u2014 no host, no dot segments, no query (use query)`);
1112
+ const query = i["query"];
1113
+ const req = withoutUndefined({ method, path: p, query, body: i["body"] });
1114
+ if (i["dry_run"] === true) return { dryRun: true, request: planned(req) };
1115
+ const confirm = i["confirm"];
1116
+ if (isDeletion(req)) {
1117
+ const t = now();
1118
+ for (const [k, v] of confirms) if (v.expires <= t) confirms.delete(k);
1119
+ if (confirm === void 0 && opts.oneRequest === true)
1120
+ return fail("agent_cannot_delete", "Nothing was sent, and it will not be: the platform refuses an agent any deletion. A person deletes in the app.");
1121
+ if (confirm === void 0) {
1122
+ const value = randomBytes(24).toString("base64url");
1123
+ confirms.set(value, { fingerprint: fingerprint(req), expires: t + CONFIRM_TTL_MS });
1124
+ return {
1125
+ preview: {
1126
+ action: "delete",
1127
+ method,
1128
+ path: p,
1129
+ confirm: value,
1130
+ expiresInSeconds: CONFIRM_TTL_MS / 1e3,
1131
+ note: "Nothing was sent. Repeat the same call with confirm to send it. The platform refuses an agent any deletion (agent_cannot_delete, bulk_delete_needs_person): a person deletes from the dashboard."
1132
+ }
1133
+ };
1134
+ }
1135
+ const held = confirms.get(confirm);
1136
+ confirms.delete(confirm);
1137
+ if (held === void 0 || held.fingerprint !== fingerprint(req))
1138
+ return fail("confirm_invalid", "confirm is unknown, expired, used, or for another request \u2014 repeat the call without it to get a new preview");
1139
+ } else if (confirm !== void 0) {
1140
+ req.query = { ...query, confirm };
1141
+ }
1142
+ const res = await call(req);
1143
+ return { status: res.status, body: res.body };
1144
+ }
1145
+ };
1146
+ return {
1147
+ sessionId,
1148
+ scope: () => scope,
1149
+ visibleTools,
1150
+ async execute(name, input) {
1151
+ const handler = isPluneToolName(name) ? handlers[name] : void 0;
1152
+ if (handler === void 0) return fail("unknown_tool", `No such tool: ${name}.`);
1153
+ const tool = pluneTool(name);
1154
+ const parsed = tool.input.safeParse(input ?? {});
1155
+ if (!parsed.success) return fail("invalid_input", `The input does not fit: ${zodMessage(parsed.error)}`);
1156
+ const args = parsed.data;
1157
+ const writes = name === "plune_api_request" ? rawWrites(str(args["method"]), str(args["path"])) : tool.write;
1158
+ if (writes && scope === "read" && args["dry_run"] !== true) return fail("read_only_token", readScopeMessage(`${name} is refused before any request`));
1159
+ try {
1160
+ const out = await handler(args);
1161
+ return "ok" in out && typeof out["ok"] === "boolean" && ("error" in out || "data" in out) ? out : { ok: true, data: out };
1162
+ } catch (err) {
1163
+ return { ok: false, error: errorOf(err) };
1164
+ }
1165
+ }
1166
+ };
1167
+ }
1168
+
1169
+ // src/mcp/server.ts
1170
+ var annotationsOf = (tool) => ({
1171
+ title: tool.title,
1172
+ readOnlyHint: !tool.write,
1173
+ destructiveHint: tool.name === "plune_api_request",
1174
+ openWorldHint: false
1175
+ });
1176
+ var listed = (tool) => ({
1177
+ name: tool.name,
1178
+ title: tool.title,
1179
+ description: tool.description,
1180
+ inputSchema: z4.toJSONSchema(tool.input, { target: "draft-2020-12", io: "input" }),
1181
+ outputSchema: z4.toJSONSchema(tool.output, { target: "draft-2020-12", io: "output" }),
1182
+ annotations: annotationsOf(tool)
1183
+ });
1184
+ function toResult(outcome) {
1185
+ if (outcome.ok) {
1186
+ return { content: [{ type: "text", text: JSON.stringify(outcome.data) }], structuredContent: outcome.data };
1187
+ }
1188
+ return {
1189
+ isError: true,
1190
+ content: [{ type: "text", text: outcome.error.message }],
1191
+ structuredContent: { error: outcome.error }
1192
+ };
1193
+ }
1194
+ function createPluneMcpServer(opts, era, traits = {}) {
1195
+ const { version, ...executorOptions } = opts;
1196
+ const listChanged = traits.listChanged ?? true;
1197
+ const fixed = era === "modern" || !listChanged;
1198
+ const executor = createPluneToolExecutor({
1199
+ ...executorOptions,
1200
+ userAgent: executorOptions.userAgent ?? `plune-cli/${version} mcp`,
1201
+ fixedToolList: fixed,
1202
+ oneRequest: !listChanged
1203
+ });
1204
+ const server = new McpServer({ name: "plune", version }, { capabilities: { tools: { listChanged } } });
1205
+ const registered = /* @__PURE__ */ new Map();
1206
+ const sync = () => {
1207
+ const visible = new Set(executor.visibleTools());
1208
+ for (const [name, tool] of registered) {
1209
+ if (visible.has(name) && !tool.enabled) tool.enable();
1210
+ else if (!visible.has(name) && tool.enabled) tool.disable();
1211
+ }
1212
+ };
1213
+ for (const tool of PLUNE_TOOLS) {
1214
+ if (!offeredTo(tool, opts.scope)) continue;
1215
+ const handle = server.registerTool(
1216
+ tool.name,
1217
+ {
1218
+ title: tool.title,
1219
+ description: tool.description,
1220
+ inputSchema: tool.input,
1221
+ outputSchema: tool.output,
1222
+ annotations: annotationsOf(tool)
1223
+ },
1224
+ async (args) => {
1225
+ const outcome = await executor.execute(tool.name, args);
1226
+ if (!fixed) sync();
1227
+ return toResult(outcome);
1228
+ }
1229
+ );
1230
+ registered.set(tool.name, handle);
1231
+ }
1232
+ if (fixed) {
1233
+ const tools = PLUNE_TOOLS.filter((t) => defaultVisibleTools(opts.scope).includes(t.name)).map(listed);
1234
+ server.server.setRequestHandler("tools/list", () => ({ tools }));
1235
+ } else sync();
1236
+ return server;
1237
+ }
1238
+
1239
+ // src/mcp/http.ts
1240
+ var METHOD_NOT_ALLOWED = JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32e3, message: "Method not allowed." } });
1241
+ async function asJson(response) {
1242
+ if (!(response.headers.get("content-type") ?? "").startsWith("text/event-stream")) return response;
1243
+ const answers = (await response.text()).split(/\r?\n/).filter((line) => line.startsWith("data:") && line.length > "data:".length).map((line) => JSON.parse(line.slice("data:".length))).filter((message) => message.method === void 0);
1244
+ if (answers.length === 0) return new Response(null, { status: 202 });
1245
+ return new Response(JSON.stringify(answers.length === 1 ? answers[0] : answers), { status: response.status, headers: { "content-type": "application/json" } });
1246
+ }
1247
+ function createPluneMcpHttpHandler(opts) {
1248
+ const callers = new AsyncLocalStorage();
1249
+ const handler = createMcpHandler(
1250
+ (ctx) => {
1251
+ const caller = callers.getStore();
1252
+ if (caller === void 0) throw new Error("no caller for this request");
1253
+ return createPluneMcpServer({ ...caller, version: opts.version }, ctx.era, { listChanged: false });
1254
+ },
1255
+ { responseMode: "json", ...opts.onerror === void 0 ? {} : { onerror: opts.onerror } }
1256
+ );
1257
+ return async (request, caller) => {
1258
+ if (request.method.toUpperCase() !== "POST") {
1259
+ return new Response(METHOD_NOT_ALLOWED, { status: 405, headers: { allow: "POST", "content-type": "application/json" } });
1260
+ }
1261
+ return asJson(await callers.run(caller, () => handler.fetch(request)));
1262
+ };
1263
+ }
1264
+ export {
1265
+ createPluneMcpHttpHandler
1266
+ };