pi-dev-flow 0.100.0 → 0.100.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,22 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.100.2] - 2026-12-04
8
+
9
+ **Jira sync has one path: the Atlassian MCP server with a scoped token.**
10
+
11
+ ### Changed
12
+ - **Jira sync has one path: the Atlassian MCP server with a scoped token.** dev-flow used to retry some calls through Jira's REST API. Those calls were statuses, comments, attachments and issue creation. 0.100.1 also tried a Basic header when Bearer failed. But a token works on only one of these paths: a scoped token works only on MCP, and a plain one gets only the MCP search tool. So the fallbacks could never succeed, and when they failed they hid the real error. They are gone, and `/flow jira login` now asks only for the site and the token. Older `jira.json` files still load; the `email` and `auth` fields in them are ignored. `JIRA_EMAIL` is no longer needed.
13
+ - **Login and `flow jira init` check everything sync needs up front.** They confirm the token reaches the site and the server offers every tool dev-flow calls. If a tool is missing, they name the scope the token lacks. An unreachable site and a non-scoped token each get an error that says how to fix it.
14
+ - **MCP calls retry transient failures.** 429s, 5xx answers, timeouts and dropped connections are retried with backoff, honouring `Retry-After`. A write is retried only when the server said it did not run it (429 or 503), so a lost answer never posts a comment or creates an issue twice. Reply checks now page through the newest 100 comments instead of 20.
15
+
16
+ ## [0.100.1] - 2026-12-04
17
+
18
+ **Jira sync works with a scoped API token.**
19
+
20
+ ### Fixed
21
+ - **Jira sync works with a scoped API token.** dev-flow sent the token to Atlassian's MCP server as Basic `email:token`. With a scoped token, which is the kind the setup asks for, the server accepted the connection but saw no site, so every call failed with *Cloud id … isn't explicitly granted by the user*. That broke `flow jira init`, linking and creating issues, status moves, mirrored questions and the reply watch. It also broke the `atlassian` tools given to the agent. dev-flow now sends the token as `Bearer`. It keeps Basic as a fallback for a plain token, using whichever one can see the site. The scheme that worked is saved with the login. Jira REST calls still use Basic.
22
+
7
23
  ## [0.100.0] - 2026-12-03
8
24
 
9
25
  **Flows on one machine no longer deploy over each other at verify.**
package/docs/jira.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  Optional. It is off until you run `flow jira init` in a project. Once on, a flow can start from a Jira issue. Every question dev-flow asks you is also posted on the issue, with the plan and screenshots attached. You can answer there, with a comment or by moving the issue, and the flow carries on.
4
4
 
5
- It talks to Atlassian's official **Rovo MCP server** (`https://mcp.atlassian.com/v2/mcp`). It uses that server's tools for everything, except two calls the server has no tool for, which go to Jira's REST API with the same token (see [Limits](#limits)). Jira Cloud only.
5
+ It talks to Atlassian's official **Rovo MCP server** (`https://mcp.atlassian.com/v2/mcp`). That server is its only path to Jira: every read and write goes through its tools, and nothing goes to Jira's REST API. Jira Cloud only.
6
6
 
7
7
  ## Setup
8
8
 
9
- 1. **Create a scoped API token for the Atlassian MCP app** at id.atlassian.com → Security → API tokens → *Create API token with scopes*. Give it `read:jira:agent-interface` and `write:jira:agent-interface`; `search:jira:agent-interface` is optional. An org admin must have turned on API-token authentication for the Rovo MCP server (Atlassian Administration → Rovo MCP server). A plain token (*Create API token*) does not work: with one, the MCP server offers only its search tool.
10
- 2. **Run `/flow jira login [site]`** and type the site, your email and the token into its dialogs. dev-flow checks them against the MCP server, then saves them to `~/.pi/agent/dev-flow/jira.json` (mode 0600). The token never passes through the chat or the agent, and is never written to `project.md`. You can use environment variables instead: `JIRA_SITE`, `JIRA_EMAIL` and `JIRA_API_TOKEN` override the file.
9
+ 1. **Create a scoped API token for the Atlassian MCP app** at id.atlassian.com → Security → API tokens → *Create API token with scopes*. Give it `read:jira:agent-interface` and `write:jira:agent-interface`; `search:jira:agent-interface` is optional. An org admin must have turned on API-token authentication for the Rovo MCP server (Atlassian Administration → Rovo MCP server). A plain token (*Create API token*) does not work: with one, the MCP server offers only its search tool. dev-flow sends the token as `Authorization: Bearer <token>`. No email is needed.
10
+ 2. **Run `/flow jira login [site]`** and type the site and the token into its dialogs. dev-flow checks the token against the MCP server before it saves anything. The token must reach the site and name your account, and the server must offer every tool dev-flow uses. If one is missing, the check names the scope the token lacks. The token is saved to `~/.pi/agent/dev-flow/jira.json` (mode 0600). It never passes through the chat or the agent, and is never written to `project.md`. You can use environment variables instead: `JIRA_SITE` and `JIRA_API_TOKEN` override the file.
11
11
  3. **Ask the agent to set up Jira sync.** It runs `flow jira init`, which asks you one question at a time:
12
12
  - **Jira project?** Which project this repo syncs with.
13
13
  - **Issue types?** The types a flow may start from, such as Story or Bug.
@@ -65,5 +65,6 @@ In a synced project, dev-flow also registers the Atlassian MCP server for the ag
65
65
 
66
66
  - Jira Cloud only. The Rovo MCP server does not serve Jira Data Center.
67
67
  - Attachments use the MCP server's two-step upload. Step one returns a short-lived Atlassian Media upload as a `curl` command. dev-flow never runs it. It reads the URL and token from the command, accepting only an https request to `api.media.atlassian.com`, sends the file itself, then attaches the file with step two.
68
- - If an MCP call can't do the job, dev-flow retries it through Jira's REST API with the same token. A token scoped to the MCP app is refused there, so those retries only help with a token that also has Jira REST scopes.
68
+ - MCP only. A scoped token works on the MCP server and nowhere else, so there is no REST fallback. Transient failures are retried with backoff: 429s, 5xx answers, timeouts and dropped connections. A write, such as a comment, a new issue, a transition or an attachment, is retried only when the server answered 429 or 503, meaning it did not run the request. A write is never sent twice because its answer was lost.
69
+ - Reply checks read the newest 100 comments on the issue, 20 per request.
69
70
  - dev-flow polls Jira; it does not use webhooks, which would need a public URL for Jira to call.
@@ -36,7 +36,7 @@ import { foldView, pluginUpstream } from "../src/runtime/reflect.ts";
36
36
  import { type FlowHooks, runFlow } from "../src/runtime/gates.ts";
37
37
  import { JiraWatch } from "../src/runtime/jira-watch.ts";
38
38
  import { mirrorClosingMessage, disarmWatch, jiraSeams, resetJiraClients } from "../src/runtime/jira.ts";
39
- import { basicAuth, loadCreds, normSite, saveCreds } from "../src/jira/creds.ts";
39
+ import { bearer, loadCreds, normSite, saveCreds } from "../src/jira/creds.ts";
40
40
  import { JiraClient, MCP_URL } from "../src/jira/client.ts";
41
41
  import type { Relay } from "../src/jira/sync.ts";
42
42
  import { grantCheck, grantRecord, isFriction, lastOperatorText, newGrantLedger, operatorMessageCount, type RefusalStreak } from "../src/runtime/grants.ts";
@@ -294,29 +294,26 @@ export default function devFlow(pi: ExtensionAPI) {
294
294
  const creds = loadCreds(cfg.jira.site, jiraSeams.env ?? process.env, jiraSeams.credsFile);
295
295
  if (!creds) return;
296
296
  try {
297
- pi.registerMcpServer?.("atlassian", { url: MCP_URL, headers: { Authorization: basicAuth(creds) }, exposure: "deferred", description: `Atlassian Jira/Confluence on ${creds.site} (dev-flow Jira sync: project ${cfg.jira.project})` });
297
+ pi.registerMcpServer?.("atlassian", { url: MCP_URL, headers: { Authorization: bearer(creds) }, exposure: "deferred", description: `Atlassian Jira/Confluence on ${creds.site} (dev-flow Jira sync: project ${cfg.jira.project})` });
298
298
  } catch {
299
299
  /* another extension owns the name, or no MCP support: the sync itself does not need it */
300
300
  }
301
301
  };
302
302
  /** /flow jira login [site] — the operator's own dialog: the token never passes through the chat or the agent. */
303
303
  const jiraLogin = async (ctx: ExtensionContext, root: string, siteArg?: string): Promise<string> => {
304
- if (!ctx.hasUI) return "flow jira login needs a dialog — set JIRA_SITE, JIRA_EMAIL and JIRA_API_TOKEN instead";
304
+ if (!ctx.hasUI) return "flow jira login needs a dialog — set JIRA_SITE and JIRA_API_TOKEN instead";
305
305
  const cfg = initiated(root) ? loadProject(dfDir(root)).cfg : undefined;
306
306
  const site = siteArg ?? cfg?.jira?.site ?? (await ctx.ui.input("Jira site", "acme.atlassian.net"));
307
307
  if (!site?.trim()) return "login cancelled";
308
- const prev = loadCreds(site, {}, jiraSeams.credsFile);
309
- const email = await ctx.ui.input(`Atlassian account email for ${normSite(site)}`, prev?.email ?? "you@example.com");
310
- if (!email?.trim()) return "login cancelled";
311
- const token = await ctx.ui.input("Atlassian API token (id.atlassian.com → Security → API tokens)", "paste the token");
308
+ const token = await ctx.ui.input("Scoped Atlassian API token (id.atlassian.com → Security → API tokens → Create API token with scopes: read:jira:agent-interface, write:jira:agent-interface)", "paste the token");
312
309
  if (!token?.trim()) return "login cancelled";
313
- const probe = new JiraClient({ site: normSite(site), email: email.trim(), token: token.trim(), source: "file" }, { fetch: jiraSeams.fetch });
314
- const me = await probe.me();
315
- if (!me.ok) return `not saved — the Atlassian MCP server refused the token: ${me.error}`;
316
- saveCreds(site, email, token, jiraSeams.credsFile);
310
+ const probe = new JiraClient({ site: normSite(site), token: token.trim(), source: "file" }, { fetch: jiraSeams.fetch });
311
+ const ok = await probe.check();
312
+ if (!ok.ok) return `not saved — ${ok.error}`;
313
+ saveCreds(site, token, jiraSeams.credsFile);
317
314
  resetJiraClients();
318
315
  if (cfg) registerAtlassianMcp(cfg);
319
- return `Jira login saved for ${normSite(site)} — authenticated as ${me.value.displayName}. ${cfg?.jira ? "Jira sync is ready." : "Next: flow jira init picks the project, issue types and status mapping."}`;
316
+ return `Jira login saved for ${normSite(site)} — authenticated as ${ok.value.displayName}. ${cfg?.jira ? "Jira sync is ready." : "Next: flow jira init picks the project, issue types and status mapping."}`;
320
317
  };
321
318
 
322
319
  pi.registerCommand("flow", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.100.0",
3
+ "version": "0.100.2",
4
4
  "description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,23 +1,22 @@
1
1
  /**
2
- * Jira operations over the official Atlassian Rovo MCP server (src/jira/mcp.ts), with the same API token
3
- * used against Jira's REST API only where the MCP server offers no tool for the job (a fallback per call,
4
- * never a second configuration).
2
+ * Jira operations over the official Atlassian Rovo MCP server (src/jira/mcp.ts) — dev-flow's only path to
3
+ * Jira. A scoped API token works there and nowhere else (Jira's REST API refuses it), so there is no REST
4
+ * fallback: one path, retried on transient failures, with errors that name the fix.
5
5
  *
6
- * Tool names and argument names are resolved against the server's live `tools/list`: v2 renamed most v1
7
- * tools (getTransitionsForJiraIssue → listJiraIssueTransitions, …) and the argument spellings are only
8
- * published as schemas, so each operation names its candidates and the first one offered wins.
6
+ * Tool names and argument names are resolved against the server's live `tools/list`: the argument spellings
7
+ * are only published as schemas, so each operation names its candidates and the first one offered wins.
9
8
  *
10
9
  * Every operation returns a JiraResult — it never throws into a gate.
11
10
  */
12
11
  import { readFileSync } from "node:fs";
13
12
  import path from "node:path";
14
- import { basicAuth, type JiraCreds } from "./creds.ts";
15
- import { type FetchLike, McpClient, type McpTool, resultText, resultValue } from "./mcp.ts";
13
+ import { bearer, type JiraCreds } from "./creds.ts";
14
+ import { type FetchLike, McpClient, type McpOptions, type McpTool, resultText, resultValue } from "./mcp.ts";
16
15
  import type { StatusInfo } from "./config.ts";
17
16
 
18
17
  export const MCP_URL = process.env.JIRA_MCP_URL ?? "https://mcp.atlassian.com/v2/mcp?tools=all";
19
18
 
20
- export type JiraResult<T> = { ok: true; value: T; via?: "mcp" | "rest" } | { ok: false; error: string };
19
+ export type JiraResult<T> = { ok: true; value: T } | { ok: false; error: string };
21
20
 
22
21
  export interface JiraUser {
23
22
  accountId: string;
@@ -54,11 +53,27 @@ const TOOLS = {
54
53
  upload: ["uploadAttachmentToJiraIssue"],
55
54
  transitions: ["listJiraIssueTransitions", "getTransitionsForJiraIssue"],
56
55
  transition: ["transitionJiraIssue"],
57
- search: ["searchJiraIssuesUsingJql"],
58
56
  create: ["createJiraIssue"],
59
57
  } as const;
60
58
  type Op = keyof typeof TOOLS;
61
59
 
60
+ /** Ops that change nothing: a lost answer may be asked for again. The rest (comment, upload, transition,
61
+ * create) are retried only when the server said it did not run them. */
62
+ const READ_OPS: ReadonlySet<Op> = new Set<Op>(["me", "resources", "projects", "issueTypes", "statuses", "issue", "comments", "transitions"]);
63
+
64
+ const COMMENTS_PAGE = 20; // the server's cap per page
65
+ const COMMENTS_MAX = 100;
66
+
67
+ const missingTool = (op: Op) =>
68
+ `the Atlassian MCP server offers this token no ${TOOLS[op].join("/")} tool — the token needs the ${READ_OPS.has(op) ? "read" : "write"}:jira:agent-interface scope`;
69
+
70
+ /** Add the fix to the known MCP failures. */
71
+ function explain(msg: string): string {
72
+ if (/isn't explicitly granted|not explicitly granted/i.test(msg))
73
+ return `${msg} — the token cannot reach this site: it must be a scoped API token (read:jira:agent-interface, write:jira:agent-interface) of an account on it; the operator re-runs /flow jira login`;
74
+ return msg;
75
+ }
76
+
62
77
  // logical argument → candidate schema property names
63
78
  const ARGS: Record<string, string[]> = {
64
79
  cloudId: ["cloudId"],
@@ -76,12 +91,10 @@ const ARGS: Record<string, string[]> = {
76
91
  mode: ["mode"],
77
92
  view: ["view"],
78
93
  order: ["orderBy"],
79
- // v1-style uploads take content; v2 takes a local filePath and hands back an Atlassian Media request (uploadTwoPhase)
80
- file: ["fileContent", "base64Content"],
94
+ startAt: ["startAt"],
95
+ // v2 uploads take a local filePath and hand back an Atlassian Media request, then the media fileId
81
96
  filePath: ["filePath"],
82
97
  fileId: ["fileId"],
83
- filename: ["filename", "fileName", "name"],
84
- mime: ["mimeType", "contentType"],
85
98
  };
86
99
 
87
100
  const str = (v: unknown) => (typeof v === "string" ? v : v == null ? "" : String(v));
@@ -133,25 +146,6 @@ export function adfText(node: unknown): string {
133
146
  return /^(paragraph|heading|listItem|codeBlock|blockquote|bulletList|orderedList|rule)$/.test(str(n.type)) ? `${kids}\n` : kids;
134
147
  }
135
148
 
136
- /** Markdown-ish text → a minimal ADF document (paragraphs and code blocks) — for REST, which takes no markdown. */
137
- export function toAdf(text: string): unknown {
138
- const content: unknown[] = [];
139
- const parts = text.split(/```[^\n]*\n([\s\S]*?)```/);
140
- parts.forEach((part, i) => {
141
- if (i % 2 === 1) return void content.push({ type: "codeBlock", content: part ? [{ type: "text", text: part.replace(/\n$/, "") }] : [] });
142
- for (const para of part.split(/\n{2,}/)) {
143
- const lines = para.split("\n").filter((l, j, a) => l || j < a.length - 1);
144
- if (!lines.join("").trim()) continue;
145
- const inl: unknown[] = [];
146
- lines.forEach((l, j) => {
147
- if (j) inl.push({ type: "hardBreak" });
148
- if (l) inl.push({ type: "text", text: l });
149
- });
150
- content.push({ type: "paragraph", content: inl });
151
- }
152
- });
153
- return { type: "doc", version: 1, content };
154
- }
155
149
 
156
150
  const MIME: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".md": "text/markdown", ".txt": "text/plain", ".json": "application/json", ".pdf": "application/pdf" };
157
151
  export const mimeOf = (file: string) => MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream";
@@ -162,14 +156,12 @@ export class JiraClient {
162
156
  private readonly fetchFn: FetchLike;
163
157
  private cloudIdP: Promise<string> | undefined;
164
158
  private cloudIdFixed: string | undefined;
165
- /** the REST base a scoped token needs, once the site URL refused it */
166
- private gateway: string | undefined;
167
159
 
168
- constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string } = {}) {
160
+ constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string; mcp?: McpOptions } = {}) {
169
161
  this.creds = creds;
170
162
  this.fetchFn = opts.fetch ?? (globalThis.fetch as unknown as FetchLike);
171
163
  this.cloudIdFixed = opts.cloudId;
172
- this.mcp = new McpClient(opts.mcpUrl ?? MCP_URL, { authorization: basicAuth(creds) }, this.fetchFn);
164
+ this.mcp = new McpClient(opts.mcpUrl ?? MCP_URL, { authorization: bearer(creds) }, this.fetchFn, opts.mcp);
173
165
  }
174
166
 
175
167
  get site() {
@@ -204,75 +196,55 @@ export class JiraClient {
204
196
  private async call(op: Op, logical: Record<string, unknown>): Promise<JiraResult<unknown>> {
205
197
  try {
206
198
  const t = await this.tool(op);
207
- if (!t) return { ok: false, error: `the Atlassian MCP server offers no ${TOOLS[op].join("/")} tool` };
199
+ if (!t) return { ok: false, error: missingTool(op) };
208
200
  const needsCloud = t.inputSchema?.properties && "cloudId" in t.inputSchema.properties;
209
201
  const args = this.args(t, { ...(needsCloud ? { cloudId: await this.cloudId() } : {}), ...logical });
210
- const r = await this.mcp.callTool(t.name, args);
211
- if (r.isError) return { ok: false, error: `${t.name}: ${resultText(r).slice(0, 400)}` };
212
- return { ok: true, value: resultValue(r), via: "mcp" };
202
+ const r = await this.mcp.callTool(t.name, args, { idempotent: READ_OPS.has(op) });
203
+ if (r.isError) return { ok: false, error: explain(`${t.name}: ${resultText(r).slice(0, 400)}`) };
204
+ return { ok: true, value: resultValue(r) };
213
205
  } catch (e) {
214
- return { ok: false, error: (e as Error).message };
206
+ return { ok: false, error: explain((e as Error).message) };
215
207
  }
216
208
  }
217
209
 
218
- /** The site's cloudId: configured, else looked up among the token's accessible resources, else the site
219
- * host (the Atlassian tools accept a site URL where they take a cloudId). */
210
+ /** The site's cloudId: configured, else the token's accessible resource for this site. A site the token
211
+ * cannot reach is an error here, not a guess passed on to every call. */
220
212
  cloudId(): Promise<string> {
221
213
  if (this.cloudIdFixed) return Promise.resolve(this.cloudIdFixed);
222
214
  this.cloudIdP ??= (async () => {
223
- try {
224
- const t = await this.tool("resources");
225
- if (t) {
226
- const r = await this.mcp.callTool(t.name, {});
227
- const hit = arr(resultValue(r)).map(rec).find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
228
- if (hit?.cloudId ?? hit?.id) return str(hit.cloudId ?? hit.id);
229
- }
230
- } catch {
231
- /* fall through */
232
- }
233
- try {
234
- const res = await this.fetchFn(`https://${this.creds.site}/_edge/tenant_info`, { method: "GET", headers: {} });
235
- if (res.ok) {
236
- const id = str(rec(JSON.parse(await res.text())).cloudId);
237
- if (id) return id;
238
- }
239
- } catch {
240
- /* fall through */
241
- }
242
- return this.creds.site;
243
- })();
215
+ const t = await this.tool("resources");
216
+ if (!t) throw new Error(missingTool("resources"));
217
+ const r = await this.mcp.callTool(t.name, {}, { idempotent: true });
218
+ if (r.isError) throw new Error(`${t.name}: ${resultText(r).slice(0, 300)}`);
219
+ const sites = arr(resultValue(r), "resources").map(rec);
220
+ const hit = sites.find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
221
+ const id = str(hit?.cloudId ?? hit?.id);
222
+ if (!id)
223
+ throw new Error(
224
+ sites.length
225
+ ? `the token reaches ${sites.map((x) => str(x.url).replace(/^https?:\/\//, "")).join(", ")}, not ${this.creds.site}`
226
+ : `the token reaches no Atlassian site — it must be a scoped API token (read:jira:agent-interface, write:jira:agent-interface) of an account on ${this.creds.site}`,
227
+ );
228
+ return id;
229
+ })().catch((e) => {
230
+ this.cloudIdP = undefined;
231
+ throw e;
232
+ });
244
233
  return this.cloudIdP;
245
234
  }
246
235
 
247
- private async restBase(): Promise<string> {
248
- return this.gateway ?? `https://${this.creds.site}/rest/api/3`;
249
- }
250
-
251
- /** Jira REST with the same token — only for what the MCP server cannot do. */
252
- private async rest(method: string, p: string, body?: unknown, extra: Record<string, string> = {}): Promise<JiraResult<unknown>> {
236
+ /** Everything sync needs, checked once: the token reaches the site, names its user, and the server offers
237
+ * every tool dev-flow calls (a missing write tool means a missing write scope). */
238
+ async check(): Promise<JiraResult<JiraUser>> {
253
239
  try {
254
- const headers: Record<string, string> = { authorization: basicAuth(this.creds), accept: "application/json", ...extra };
255
- let payload: string | undefined;
256
- if (body !== undefined && typeof body === "string") payload = body;
257
- else if (body !== undefined) {
258
- headers["content-type"] = "application/json";
259
- payload = JSON.stringify(body);
260
- }
261
- let res = await this.fetchFn(`${await this.restBase()}${p}`, { method, headers, body: payload });
262
- if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
263
- // a scoped API token answers only through api.atlassian.com/ex/jira/<cloudId>
264
- const id = await this.cloudId();
265
- if (/^[0-9a-f-]{36}$/.test(id)) {
266
- this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
267
- res = await this.fetchFn(`${this.gateway}${p}`, { method, headers, body: payload });
268
- }
269
- }
270
- const text = await res.text();
271
- if (!res.ok) return { ok: false, error: `Jira REST ${method} ${p}: HTTP ${res.status} ${text.slice(0, 300)}` };
272
- return { ok: true, value: text ? JSON.parse(text) : undefined, via: "rest" };
240
+ await this.cloudId();
241
+ const tools = await this.mcp.listTools();
242
+ const missing = (Object.keys(TOOLS) as Op[]).filter((op) => !TOOLS[op].some((n) => tools.some((x) => x.name === n)));
243
+ if (missing.length) return { ok: false, error: missing.map(missingTool).join("; ") };
273
244
  } catch (e) {
274
- return { ok: false, error: (e as Error).message };
245
+ return { ok: false, error: explain((e as Error).message) };
275
246
  }
247
+ return this.me();
276
248
  }
277
249
 
278
250
  async me(): Promise<JiraResult<JiraUser>> {
@@ -296,8 +268,7 @@ export class JiraClient {
296
268
  return { ok: true, value: arr(r.value).map(rec).map((t) => ({ id: str(t.id), name: str(t.name), subtask: t.subtask === true || t.hierarchyLevel === -1 })).filter((t) => t.name) };
297
269
  }
298
270
 
299
- /** The statuses of each issue type's workflow in a project. MCP `listJiraStatuses` when it answers per issue
300
- * type, else REST `/project/{key}/statuses` (the one call grouped by issue type). */
271
+ /** The statuses of each issue type's workflow in a project (`listJiraStatuses`, mode "project"). */
301
272
  async statuses(project: string): Promise<JiraResult<Record<string, StatusInfo[]>>> {
302
273
  const toInfo = (s: Record<string, unknown>): StatusInfo => ({ name: str(s.name), category: str(rec(s.statusCategory).key ?? s.statusCategory ?? s.category) || undefined });
303
274
  const grouped = (v: unknown) => {
@@ -314,10 +285,9 @@ export class JiraClient {
314
285
  return Object.fromEntries(list.map((t) => [str(t.name), (t.statuses as unknown[]).map(rec).map(toInfo)]));
315
286
  };
316
287
  const m = await this.call("statuses", { mode: "project", project });
317
- if (m.ok && grouped(m.value)) return { ok: true, value: grouped(m.value)!, via: "mcp" };
318
- const r = await this.rest("GET", `/project/${encodeURIComponent(project)}/statuses`);
319
- if (r.ok && grouped(r.value)) return { ok: true, value: grouped(r.value)!, via: "rest" };
320
- return { ok: false, error: !m.ok ? m.error : !r.ok ? r.error : "no per-issue-type statuses in the answer" };
288
+ if (!m.ok) return m;
289
+ const g = grouped(m.value);
290
+ return g ? { ok: true, value: g } : { ok: false, error: `listJiraStatuses: no per-issue-type statuses in ${JSON.stringify(m.value).slice(0, 200)}` };
321
291
  }
322
292
 
323
293
  async issue(key: string): Promise<JiraResult<JiraIssue>> {
@@ -341,17 +311,25 @@ export class JiraClient {
341
311
  };
342
312
  }
343
313
 
314
+ /** The newest comments, newest first: pages of 20 (the server's cap) up to COMMENTS_MAX. */
344
315
  async comments(key: string): Promise<JiraResult<JiraComment[]>> {
345
316
  const toC = (c: Record<string, unknown>): JiraComment => {
346
317
  const a = rec(c.author);
347
318
  return { id: str(c.id), authorId: str(a.accountId), authorName: str(a.displayName), body: adfText(c.body ?? c.renderedBody).trim(), created: str(c.created), updated: str(c.updated) || undefined };
348
319
  };
349
- // "full": the default compact view leaves out the author's accountId, which decides who answered (its page caps at 20)
350
- const m = await this.call("comments", { issue: key, max: 20, order: "-created", view: "full" });
351
- if (m.ok) return { ok: true, value: arr(m.value).map(rec).map(toC).filter((c) => c.id), via: "mcp" };
352
- const r = await this.rest("GET", `/issue/${encodeURIComponent(key)}/comment?orderBy=-created&maxResults=100`);
353
- if (r.ok) return { ok: true, value: arr(r.value).map(rec).map(toC).filter((c) => c.id), via: "rest" };
354
- return m;
320
+ const out: JiraComment[] = [];
321
+ for (let startAt = 0; out.length < COMMENTS_MAX; ) {
322
+ // "full": the default compact view leaves out the author's accountId, which decides who answered
323
+ const m = await this.call("comments", { issue: key, max: COMMENTS_PAGE, order: "-created", view: "full", ...(startAt ? { startAt } : {}) });
324
+ if (!m.ok) return out.length ? { ok: true, value: out } : m;
325
+ const page = arr(m.value).map(rec);
326
+ out.push(...page.map(toC).filter((c) => c.id));
327
+ const v = rec(m.value);
328
+ const total = typeof v.total === "number" ? v.total : undefined;
329
+ startAt += page.length;
330
+ if (!page.length || v.isLast === true || (total !== undefined && startAt >= total) || (v.isLast === undefined && total === undefined && page.length < COMMENTS_PAGE)) break;
331
+ }
332
+ return { ok: true, value: out.slice(0, COMMENTS_MAX) };
355
333
  }
356
334
 
357
335
  /** Post a comment (markdown); returns its id. */
@@ -359,79 +337,43 @@ export class JiraClient {
359
337
  const t = await this.tool("comment").catch(() => undefined);
360
338
  const takesFormat = !!t && Object.keys(t.inputSchema?.properties ?? {}).some((p) => ARGS.format.includes(p));
361
339
  const m = await this.call("comment", { issue: key, body: markdown, ...(takesFormat ? { format: "markdown" } : {}) });
362
- if (m.ok) {
363
- const v = rec(m.value);
364
- return { ok: true, value: str(v.commentId ?? v.id ?? rec(v.comment).id), via: "mcp" };
365
- }
366
- const r = await this.rest("POST", `/issue/${encodeURIComponent(key)}/comment`, { body: toAdf(markdown) });
367
- if (r.ok) return { ok: true, value: str(rec(r.value).id), via: "rest" };
368
- return m;
340
+ if (!m.ok) return m;
341
+ const v = rec(m.value);
342
+ return { ok: true, value: str(v.commentId ?? v.id ?? rec(v.comment).id) };
369
343
  }
370
344
 
371
- /** v2's two-phase upload: phase 1 (filePath) mints a short-lived Atlassian Media upload — a curl command we
372
- * read but never run; we send the bytes ourselves; phase 2 (fileId) attaches the file to the issue. */
373
- private async uploadTwoPhase(key: string, file: string, data: Buffer): Promise<JiraResult<string>> {
374
- const p1 = await this.call("upload", { issue: key, filePath: path.resolve(file) });
375
- if (!p1.ok) return p1;
376
- const v = rec(p1.value);
377
- const req = parseUploadCommand(str(v.uploadCommand));
378
- if (!req) return { ok: false, error: "the upload step returned no Atlassian Media request dev-flow can send" };
379
- try {
380
- const res = await this.fetchFn(req.url, { method: "POST", headers: { ...req.headers, "content-type": mimeOf(file) }, body: data as unknown as string });
381
- const text = await res.text();
382
- if (!res.ok) return { ok: false, error: `Atlassian Media upload: HTTP ${res.status} ${text.slice(0, 200)}` };
383
- const j = rec(JSON.parse(text)); // rec() already unwraps { data: … }
384
- const fileId = str(j.id ?? rec(j.data).id);
385
- if (!fileId) return { ok: false, error: `Atlassian Media upload: no file id in ${text.slice(0, 200)}` };
386
- const p2 = await this.call("upload", { issue: key, fileId });
387
- return p2.ok ? { ok: true, value: path.basename(file), via: "mcp" } : p2;
388
- } catch (e) {
389
- return { ok: false, error: `Atlassian Media upload: ${(e as Error).message}` };
390
- }
391
- }
392
-
393
- /** Attach a local file: MCP (content, or the two-phase media upload), else REST multipart. */
345
+ /** Attach a local file with v2's two-phase upload: phase 1 (filePath) mints a short-lived Atlassian Media
346
+ * upload — a curl command we read but never run; we send the bytes ourselves; phase 2 (fileId) attaches the
347
+ * file to the issue. */
394
348
  async upload(key: string, file: string): Promise<JiraResult<string>> {
395
- const data = readFileSync(file);
396
349
  const name = path.basename(file);
397
- const t = await this.tool("upload").catch(() => undefined);
398
- const props = Object.keys(t?.inputSchema?.properties ?? {});
399
- let mcpError: string | undefined;
400
- if (t && props.includes("filePath") && props.includes("fileId")) {
401
- const r = await this.uploadTwoPhase(key, file, data);
402
- if (r.ok) return r;
403
- mcpError = r.error;
404
- }
405
- if (t && props.some((p) => ARGS.file.includes(p))) {
406
- const m = await this.call("upload", { issue: key, file: data.toString("base64"), filename: name, mime: mimeOf(file) });
407
- if (m.ok) return { ok: true, value: name, via: "mcp" };
350
+ const fail = (why: string): JiraResult<string> => ({ ok: false, error: `attach ${name}: ${why}` });
351
+ let data: Buffer;
352
+ try {
353
+ data = readFileSync(file);
354
+ } catch (e) {
355
+ return fail((e as Error).message);
408
356
  }
409
- const boundary = `----devflow${Date.now().toString(16)}`;
410
- const head = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name.replace(/"/g, "")}"\r\nContent-Type: ${mimeOf(file)}\r\n\r\n`;
411
- const body = Buffer.concat([Buffer.from(head), data, Buffer.from(`\r\n--${boundary}--\r\n`)]);
357
+ const p1 = await this.call("upload", { issue: key, filePath: path.resolve(file) });
358
+ if (!p1.ok) return fail(p1.error);
359
+ const req = parseUploadCommand(str(rec(p1.value).uploadCommand));
360
+ if (!req) return fail("the upload step returned no Atlassian Media request dev-flow can send");
412
361
  try {
413
- const send = async (base: string) =>
414
- this.fetchFn(`${base}/issue/${encodeURIComponent(key)}/attachments`, {
415
- method: "POST",
416
- headers: { authorization: basicAuth(this.creds), "x-atlassian-token": "no-check", "content-type": `multipart/form-data; boundary=${boundary}`, accept: "application/json" },
417
- // SAFETY: fetch accepts a Buffer body; FetchLike types it as string for the JSON paths
418
- body: body as unknown as string,
419
- });
420
- let res = await send(await this.restBase());
421
- if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
422
- const id = await this.cloudId();
423
- if (/^[0-9a-f-]{36}$/.test(id)) {
424
- this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
425
- res = await send(this.gateway);
426
- }
362
+ let res: Awaited<ReturnType<FetchLike>> | undefined;
363
+ for (let attempt = 0; attempt < 3; attempt++) {
364
+ // the upload only stores bytes under a fresh id: sending it again cannot attach twice
365
+ res = await this.fetchFn(req.url, { method: "POST", headers: { ...req.headers, "content-type": mimeOf(file) }, body: data as unknown as string });
366
+ if (res.ok || !(res.status === 429 || res.status >= 500)) break;
427
367
  }
428
- if (!res.ok) {
429
- const why = res.status === 401 || res.status === 403 || res.status === 404 ? "Jira's REST API did not accept the token either" : (await res.text()).slice(0, 200);
430
- return { ok: false, error: `attach ${name}: ${mcpError ? `${mcpError}; REST fallback: ` : ""}HTTP ${res.status} — ${why}` };
431
- }
432
- return { ok: true, value: name, via: "rest" };
368
+ const text = await res!.text();
369
+ if (!res!.ok) return fail(`Atlassian Media upload: HTTP ${res!.status} ${text.slice(0, 200)}`);
370
+ const j = rec(JSON.parse(text)); // rec() already unwraps { data: … }
371
+ const fileId = str(j.id ?? rec(j.data).id);
372
+ if (!fileId) return fail(`Atlassian Media upload: no file id in ${text.slice(0, 200)}`);
373
+ const p2 = await this.call("upload", { issue: key, fileId });
374
+ return p2.ok ? { ok: true, value: name } : fail(p2.error);
433
375
  } catch (e) {
434
- return { ok: false, error: `attach ${name}: ${(e as Error).message}` };
376
+ return fail(`Atlassian Media upload: ${(e as Error).message}`);
435
377
  }
436
378
  }
437
379
 
@@ -444,11 +386,9 @@ export class JiraClient {
444
386
  const typeVal = types?.ok ? (types.value.find((x) => x.name.toLowerCase() === type.toLowerCase())?.id ?? type) : type;
445
387
  const takesFormat = props.some((p) => ARGS.format.includes(p));
446
388
  const m = await this.call("create", { project, issueType: typeVal, summary, description: description || undefined, ...(takesFormat && description ? { format: "markdown" } : {}) });
447
- const keyOf = (v: unknown) => str(rec(v).key ?? rec(rec(v).issue).key);
448
- if (m.ok && keyOf(m.value)) return { ok: true, value: keyOf(m.value), via: "mcp" };
449
- const r = await this.rest("POST", "/issue", { fields: { project: { key: project }, issuetype: { name: type }, summary, ...(description ? { description: toAdf(description) } : {}) } });
450
- if (r.ok && keyOf(r.value)) return { ok: true, value: keyOf(r.value), via: "rest" };
451
- return m.ok ? { ok: false, error: `created, but no key in the answer: ${JSON.stringify(m.value).slice(0, 200)}` } : m;
389
+ if (!m.ok) return m;
390
+ const k = str(rec(m.value).key ?? rec(rec(m.value).issue).key);
391
+ return k ? { ok: true, value: k } : { ok: false, error: `created, but no key in the answer: ${JSON.stringify(m.value).slice(0, 200)}` };
452
392
  }
453
393
 
454
394
  async transitions(key: string): Promise<JiraResult<{ id: string; name: string; to: string }[]>> {
package/src/jira/creds.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  /**
2
- * Jira credentials — a Cloud API token sent as HTTP Basic `email:token` (the Atlassian Rovo MCP server's
3
- * API-token auth). They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by
4
- * `/flow jira login`; `JIRA_EMAIL` / `JIRA_API_TOKEN` (and optionally `JIRA_SITE`) override the file.
5
- * Never printed, never written to project.md or to a comment.
2
+ * Jira credentials — a scoped Atlassian Cloud API token (`read:jira:agent-interface`,
3
+ * `write:jira:agent-interface`) for the Atlassian Rovo MCP server, sent as `Authorization: Bearer <token>`.
4
+ * That is dev-flow's only path to Jira: no REST, no Basic auth, so no email.
5
+ *
6
+ * They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by `/flow jira login`;
7
+ * `JIRA_API_TOKEN` (with `JIRA_SITE`) overrides the file. Never printed, never written to project.md or to a
8
+ * comment. Older files carry `email` / `auth` next to the token: they still load, and those fields are ignored.
6
9
  */
7
10
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
11
  import os from "node:os";
@@ -10,7 +13,6 @@ import path from "node:path";
10
13
 
11
14
  export interface JiraCreds {
12
15
  site: string; // acme.atlassian.net
13
- email: string;
14
16
  token: string;
15
17
  source: "env" | "file";
16
18
  }
@@ -25,7 +27,7 @@ export const normSite = (s: string) =>
25
27
  .replace(/\/.*$/, "")
26
28
  .toLowerCase();
27
29
 
28
- type Store = { sites?: Record<string, { email: string; token: string }> };
30
+ type Store = { sites?: Record<string, { token: string; [legacy: string]: unknown }> };
29
31
 
30
32
  function readStore(file: string): Store {
31
33
  try {
@@ -38,20 +40,20 @@ function readStore(file: string): Store {
38
40
  /** Credentials for `site` (or for the only/first stored site when none is named), or null. */
39
41
  export function loadCreds(site?: string, env: NodeJS.ProcessEnv = process.env, file = credsPath()): JiraCreds | null {
40
42
  const want = site ? normSite(site) : env.JIRA_SITE ? normSite(env.JIRA_SITE) : undefined;
41
- if (env.JIRA_EMAIL && env.JIRA_API_TOKEN && (want || env.JIRA_SITE))
42
- return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env" };
43
+ if (env.JIRA_API_TOKEN && (want || env.JIRA_SITE)) return { site: want ?? normSite(env.JIRA_SITE!), token: env.JIRA_API_TOKEN.trim(), source: "env" };
43
44
  const sites = readStore(file).sites ?? {};
44
45
  const key = want ?? Object.keys(sites)[0];
45
46
  const hit = key ? sites[key] : undefined;
46
- return hit && key ? { site: key, email: hit.email, token: hit.token, source: "file" } : null;
47
+ return hit?.token && key ? { site: key, token: hit.token, source: "file" } : null;
47
48
  }
48
49
 
49
- export function saveCreds(site: string, email: string, token: string, file = credsPath()): void {
50
+ export function saveCreds(site: string, token: string, file = credsPath()): void {
50
51
  mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
51
52
  const store = existsSync(file) ? readStore(file) : {};
52
- store.sites = { ...(store.sites ?? {}), [normSite(site)]: { email: email.trim(), token: token.trim() } };
53
+ store.sites = { ...(store.sites ?? {}), [normSite(site)]: { token: token.trim() } };
53
54
  writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
54
55
  chmodSync(file, 0o600);
55
56
  }
56
57
 
57
- export const basicAuth = (c: Pick<JiraCreds, "email" | "token">) => `Basic ${Buffer.from(`${c.email}:${c.token}`).toString("base64")}`;
58
+ /** The MCP server's Authorization header. */
59
+ export const bearer = (c: Pick<JiraCreds, "token">) => `Bearer ${c.token}`;
package/src/jira/mcp.ts CHANGED
@@ -32,12 +32,33 @@ export interface McpCallResult {
32
32
 
33
33
  export class McpError extends Error {
34
34
  readonly status?: number;
35
- constructor(message: string, status?: number) {
35
+ /** a failure worth retrying: "network" / "timeout" (no answer), or "http" with a 429/5xx status */
36
+ readonly kind: "http" | "network" | "timeout" | "protocol";
37
+ readonly retryAfterMs?: number;
38
+ constructor(message: string, status?: number, kind: McpError["kind"] = status ? "http" : "protocol", retryAfterMs?: number) {
36
39
  super(message);
37
40
  this.status = status;
41
+ this.kind = kind;
42
+ this.retryAfterMs = retryAfterMs;
38
43
  }
39
44
  }
40
45
 
46
+ /** Whether a failed request may be sent again. A read may always be retried on a transient failure. A write
47
+ * (a comment, an issue, a transition) only when the server said it did not run it — 429 or 503 — so a lost
48
+ * answer never posts the same comment twice. */
49
+ export function retryable(e: unknown, idempotent: boolean): boolean {
50
+ if (!(e instanceof McpError)) return false;
51
+ if (e.kind === "http") return e.status === 429 || e.status === 503 || (idempotent && (e.status === 502 || e.status === 504));
52
+ return idempotent && (e.kind === "network" || e.kind === "timeout");
53
+ }
54
+
55
+ export interface McpOptions {
56
+ timeoutMs?: number;
57
+ /** waits before each retry; its length is the number of retries */
58
+ retryDelaysMs?: number[];
59
+ sleep?: (ms: number) => Promise<void>;
60
+ }
61
+
41
62
  const PROTOCOL = "2025-06-18";
42
63
 
43
64
  /** The JSON-RPC message answering `id` in an SSE body (`data:` lines, events split by a blank line). */
@@ -69,15 +90,32 @@ export class McpClient {
69
90
  private readonly headers: Record<string, string>;
70
91
  private readonly fetchFn: FetchLike;
71
92
  private readonly timeoutMs: number;
93
+ private readonly retryDelaysMs: number[];
94
+ private readonly sleep: (ms: number) => Promise<void>;
72
95
 
73
- constructor(url: string, headers: Record<string, string>, fetchFn: FetchLike = globalThis.fetch as unknown as FetchLike, timeoutMs = 30_000) {
96
+ constructor(url: string, headers: Record<string, string>, fetchFn: FetchLike = globalThis.fetch as unknown as FetchLike, opts: McpOptions = {}) {
74
97
  this.url = url;
75
98
  this.headers = headers;
76
99
  this.fetchFn = fetchFn;
77
- this.timeoutMs = timeoutMs;
100
+ this.timeoutMs = opts.timeoutMs ?? 30_000;
101
+ this.retryDelaysMs = opts.retryDelaysMs ?? [1000, 2000, 4000];
102
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
103
+ }
104
+
105
+ /** One POST, retried with backoff on a transient failure (see `retryable`). */
106
+ private async post(body: unknown, id: number | undefined, idempotent: boolean): Promise<unknown> {
107
+ for (let attempt = 0; ; attempt++) {
108
+ try {
109
+ return await this.postOnce(body, id);
110
+ } catch (e) {
111
+ if (attempt >= this.retryDelaysMs.length || !retryable(e, idempotent)) throw e;
112
+ const wait = (e as McpError).retryAfterMs ?? this.retryDelaysMs[attempt];
113
+ await this.sleep(Math.min(wait, 30_000));
114
+ }
115
+ }
78
116
  }
79
117
 
80
- private async post(body: unknown, id?: number): Promise<unknown> {
118
+ private async postOnce(body: unknown, id?: number): Promise<unknown> {
81
119
  const headers: Record<string, string> = {
82
120
  ...this.headers,
83
121
  "content-type": "application/json",
@@ -91,7 +129,7 @@ export class McpClient {
91
129
  try {
92
130
  res = await this.fetchFn(this.url, { method: "POST", headers, body: JSON.stringify(body), signal: ctl.signal });
93
131
  } catch (e) {
94
- throw new McpError(ctl.signal.aborted ? `timed out after ${this.timeoutMs / 1000}s` : `request failed: ${(e as Error).message}`);
132
+ throw ctl.signal.aborted ? new McpError(`timed out after ${this.timeoutMs / 1000}s`, undefined, "timeout") : new McpError(`request failed: ${(e as Error).message}`, undefined, "network");
95
133
  } finally {
96
134
  clearTimeout(timer);
97
135
  }
@@ -99,8 +137,14 @@ export class McpClient {
99
137
  if (sid) this.sessionId = sid;
100
138
  const text = await res.text();
101
139
  if (!res.ok) {
102
- const hint = res.status === 401 || res.status === 403 ? " — check the email and API token, and that an org admin enabled API-token auth for the Atlassian MCP server" : "";
103
- throw new McpError(`HTTP ${res.status}${hint}${text ? `: ${text.slice(0, 300)}` : ""}`, res.status);
140
+ const hint =
141
+ res.status === 401
142
+ ? " — the Atlassian MCP server refused the token (revoked, expired, or not a scoped API token); the operator re-runs /flow jira login"
143
+ : res.status === 403
144
+ ? " — the token may not use the Atlassian MCP server (an org admin enables API-token auth in Atlassian Administration → Rovo MCP server)"
145
+ : "";
146
+ const ra = Number(res.headers.get("retry-after"));
147
+ throw new McpError(`HTTP ${res.status}${hint}${text ? `: ${text.slice(0, 300)}` : ""}`, res.status, "http", Number.isFinite(ra) && ra > 0 ? ra * 1000 : undefined);
104
148
  }
105
149
  if (id === undefined) return undefined; // a notification: 202, no body
106
150
  const type = res.headers.get("content-type") ?? "";
@@ -112,16 +156,16 @@ export class McpClient {
112
156
  return msg.result;
113
157
  }
114
158
 
115
- private async request(method: string, params?: unknown): Promise<unknown> {
159
+ private async request(method: string, params: unknown, idempotent: boolean): Promise<unknown> {
116
160
  const id = this.nextId++;
117
- return this.post({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }, id);
161
+ return this.post({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) }, id, idempotent);
118
162
  }
119
163
 
120
164
  /** Handshake once; a failed handshake is retried by the next call. */
121
165
  init(): Promise<void> {
122
166
  this.ready ??= (async () => {
123
- await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pi-dev-flow", version: "1" } });
124
- await this.post({ jsonrpc: "2.0", method: "notifications/initialized" });
167
+ await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "pi-dev-flow", version: "1" } }, true);
168
+ await this.post({ jsonrpc: "2.0", method: "notifications/initialized" }, undefined, true);
125
169
  })().catch((e) => {
126
170
  this.ready = undefined;
127
171
  this.sessionId = undefined;
@@ -136,7 +180,7 @@ export class McpClient {
136
180
  const out: McpTool[] = [];
137
181
  let cursor: string | undefined;
138
182
  do {
139
- const r = (await this.request("tools/list", cursor ? { cursor } : {})) as { tools?: McpTool[]; nextCursor?: string };
183
+ const r = (await this.request("tools/list", cursor ? { cursor } : {}, true)) as { tools?: McpTool[]; nextCursor?: string };
140
184
  out.push(...(r.tools ?? []));
141
185
  cursor = r.nextCursor;
142
186
  } while (cursor);
@@ -144,17 +188,20 @@ export class McpClient {
144
188
  return out;
145
189
  }
146
190
 
147
- async callTool(name: string, args: Record<string, unknown>): Promise<McpCallResult> {
191
+ /** Call a tool. `idempotent` (a read) lets a lost answer be retried; a write is retried only when the
192
+ * server said it did not run it. */
193
+ async callTool(name: string, args: Record<string, unknown>, opts: { idempotent?: boolean } = {}): Promise<McpCallResult> {
194
+ const idem = opts.idempotent ?? false;
148
195
  await this.init();
149
196
  try {
150
- return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
197
+ return (await this.request("tools/call", { name, arguments: args }, idem)) as McpCallResult;
151
198
  } catch (e) {
152
- // an expired server session: start over once
199
+ // an expired server session: start over once (the call never reached a live session, so it did not run)
153
200
  if (e instanceof McpError && e.status === 404 && this.sessionId) {
154
201
  this.ready = undefined;
155
202
  this.sessionId = undefined;
156
203
  await this.init();
157
- return (await this.request("tools/call", { name, arguments: args })) as McpCallResult;
204
+ return (await this.request("tools/call", { name, arguments: args }, idem)) as McpCallResult;
158
205
  }
159
206
  throw e;
160
207
  }
@@ -30,7 +30,7 @@ export function jiraClient(cfg: Pick<JiraConfig, "site" | "cloudId">): { client:
30
30
  }
31
31
 
32
32
  function clientFor(creds: JiraCreds, cloudId?: string): JiraClient {
33
- const id = `${creds.site}\0${creds.email}\0${createHash("sha1").update(creds.token).digest("hex")}\0${cloudId ?? ""}\0${jiraSeams.fetch ? "seam" : ""}`;
33
+ const id = `${creds.site}\0${createHash("sha1").update(creds.token).digest("hex")}\0${cloudId ?? ""}\0${jiraSeams.fetch ? "seam" : ""}`;
34
34
  let c = clients.get(id);
35
35
  if (!c) {
36
36
  c = new JiraClient(creds, { cloudId, fetch: jiraSeams.fetch });
@@ -43,7 +43,7 @@ function clientFor(creds: JiraCreds, cloudId?: string): JiraClient {
43
43
  export const resetJiraClients = () => clients.clear();
44
44
 
45
45
  const noCreds = (site?: string) =>
46
- `no Jira credentials${site ? ` for ${site}` : ""} — the operator runs /flow jira login${site ? ` ${site}` : ""} (an Atlassian Cloud API token; stored in ~/.pi/agent/dev-flow/jira.json, mode 0600), or sets JIRA_SITE, JIRA_EMAIL and JIRA_API_TOKEN. The token never goes through the chat.`;
46
+ `no Jira credentials${site ? ` for ${site}` : ""} — the operator runs /flow jira login${site ? ` ${site}` : ""} (a scoped Atlassian Cloud API token; stored in ~/.pi/agent/dev-flow/jira.json, mode 0600), or sets JIRA_SITE and JIRA_API_TOKEN. The token never goes through the chat.`;
47
47
 
48
48
  const sha1 = (b: string | Buffer) => createHash("sha1").update(b).digest("hex");
49
49
 
@@ -58,8 +58,8 @@ export async function gateJiraInit(root: string, cfg: Config, rest: string[], fl
58
58
  const creds = loadCreds(siteArg ?? cfg.jira?.site, jiraSeams.env ?? process.env, jiraSeams.credsFile ?? credsPath());
59
59
  if (!creds) return { text: needsOperator(noCreds(siteArg ?? cfg.jira?.site), "Jira login?", "ask the operator to run /flow jira login (never ask them to paste the token into the chat); once they say it is done, re-run flow jira init"), isError: true };
60
60
  const client = clientFor(creds, cfg.jira?.site === creds.site ? cfg.jira.cloudId : undefined);
61
- const me = await client.me();
62
- if (!me.ok) return { text: `Jira authentication failed on ${creds.site} (${creds.source === "env" ? "JIRA_EMAIL/JIRA_API_TOKEN" : "stored login"}): ${me.error}\nThe Atlassian MCP server takes a Cloud API token as Basic email:token only when an org admin enabled API-token authentication for it (Atlassian Administration → Rovo MCP server). Check the email and token (/flow jira login re-enters them).`, isError: true };
61
+ const me = await client.check();
62
+ if (!me.ok) return { text: `Jira check failed on ${creds.site} (${creds.source === "env" ? "JIRA_API_TOKEN" : "stored login"}): ${me.error}`, isError: true };
63
63
  const head = `Jira: authenticated as ${me.value.displayName} on ${creds.site} (Atlassian MCP server)`;
64
64
 
65
65
  const project = flagValue(rest, "project") ?? cfg.jira?.project;