pi-dev-flow 0.100.1 → 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,15 @@ 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
+
7
16
  ## [0.100.1] - 2026-12-04
8
17
 
9
18
  **Jira sync works with a scoped API token.**
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. dev-flow sends a scoped token as `Authorization: Bearer <token>`. A scoped token sent as Basic `email:token` gets through the handshake, but every call fails with *Cloud id … isn't explicitly granted*.
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`. Login also records which auth scheme worked (`auth = bearer` or `basic`), so later sessions skip the check. You can use environment variables instead: `JIRA_SITE`, `JIRA_EMAIL` and `JIRA_API_TOKEN` override the file, and `JIRA_AUTH=bearer|basic` pins the scheme.
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 { loadCreds, mcpAuth, normSite, saveAuth, 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";
@@ -288,47 +288,32 @@ export default function devFlow(pi: ExtensionAPI) {
288
288
  return "";
289
289
  };
290
290
  /** Give the agent the Atlassian MCP server's tools (deferred: found through tool search) for a Jira-synced
291
- * project — the issue, its links, its history. A server of the same name in mcp.json wins. With no stored
292
- * auth scheme the token is probed first (Bearer, then Basic) and the one that works is remembered. */
293
- const registerAtlassianMcp = async (cfg: ReturnType<typeof loadProject>["cfg"]) => {
294
- if (!cfg.jira || !pi.registerMcpServer) return;
291
+ * project — the issue, its links, its history. A server of the same name in mcp.json wins. */
292
+ const registerAtlassianMcp = (cfg: ReturnType<typeof loadProject>["cfg"]) => {
293
+ if (!cfg.jira) return;
295
294
  const creds = loadCreds(cfg.jira.site, jiraSeams.env ?? process.env, jiraSeams.credsFile);
296
295
  if (!creds) return;
297
- let scheme = creds.auth;
298
- if (!scheme) {
299
- try {
300
- const picked = await new JiraClient(creds, { fetch: jiraSeams.fetch }).authScheme();
301
- scheme = picked.scheme;
302
- if (picked.verified && creds.source === "file") saveAuth(creds, scheme, jiraSeams.credsFile);
303
- } catch {
304
- scheme = "bearer"; // unreachable now: the scoped token's scheme
305
- }
306
- }
307
296
  try {
308
- pi.registerMcpServer("atlassian", { url: MCP_URL, headers: { Authorization: mcpAuth(creds, scheme) }, 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})` });
309
298
  } catch {
310
299
  /* another extension owns the name, or no MCP support: the sync itself does not need it */
311
300
  }
312
301
  };
313
302
  /** /flow jira login [site] — the operator's own dialog: the token never passes through the chat or the agent. */
314
303
  const jiraLogin = async (ctx: ExtensionContext, root: string, siteArg?: string): Promise<string> => {
315
- 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";
316
305
  const cfg = initiated(root) ? loadProject(dfDir(root)).cfg : undefined;
317
306
  const site = siteArg ?? cfg?.jira?.site ?? (await ctx.ui.input("Jira site", "acme.atlassian.net"));
318
307
  if (!site?.trim()) return "login cancelled";
319
- const prev = loadCreds(site, {}, jiraSeams.credsFile);
320
- const email = await ctx.ui.input(`Atlassian account email for ${normSite(site)}`, prev?.email ?? "you@example.com");
321
- if (!email?.trim()) return "login cancelled";
322
- 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");
323
309
  if (!token?.trim()) return "login cancelled";
324
- const probe = new JiraClient({ site: normSite(site), email: email.trim(), token: token.trim(), source: "file" }, { fetch: jiraSeams.fetch });
325
- const me = await probe.me();
326
- if (!me.ok) return `not saved — the Atlassian MCP server refused the token: ${me.error}`;
327
- const auth = await probe.authScheme();
328
- saveCreds(site, email, token, jiraSeams.credsFile, auth.verified ? auth.scheme : undefined);
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);
329
314
  resetJiraClients();
330
- if (cfg) await registerAtlassianMcp(cfg);
331
- 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."}`;
315
+ if (cfg) registerAtlassianMcp(cfg);
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."}`;
332
317
  };
333
318
 
334
319
  pi.registerCommand("flow", {
@@ -719,7 +704,7 @@ export default function devFlow(pi: ExtensionAPI) {
719
704
  if (!initiated(root)) return;
720
705
  const cfg = loadProject(dfDir(root)).cfg;
721
706
  if (!cfg.jira) return;
722
- void registerAtlassianMcp(cfg);
707
+ registerAtlassianMcp(cfg);
723
708
  // a question asked before this session (or before a restart) is caught up now, then watched again
724
709
  const st = boundFeature(root, sessionKey(ctx));
725
710
  if (st?.jira?.watch && !isWorkerSession(ctx)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.100.1",
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 JiraAuth, type JiraCreds, mcpAuth } 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,99 +146,22 @@ 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";
158
152
 
159
153
  export class JiraClient {
160
154
  readonly creds: JiraCreds;
161
- private readonly mcpUrl: string;
162
- private mcpP: Promise<McpClient> | undefined;
163
- /** the MCP auth scheme in use, once picked; `verified` when the site was seen through it */
164
- private picked: { scheme: JiraAuth; verified: boolean } | undefined;
155
+ readonly mcp: McpClient;
165
156
  private readonly fetchFn: FetchLike;
166
157
  private cloudIdP: Promise<string> | undefined;
167
158
  private cloudIdFixed: string | undefined;
168
- /** the REST base a scoped token needs, once the site URL refused it */
169
- private gateway: string | undefined;
170
159
 
171
- constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string } = {}) {
160
+ constructor(creds: JiraCreds, opts: { cloudId?: string; fetch?: FetchLike; mcpUrl?: string; mcp?: McpOptions } = {}) {
172
161
  this.creds = creds;
173
162
  this.fetchFn = opts.fetch ?? (globalThis.fetch as unknown as FetchLike);
174
163
  this.cloudIdFixed = opts.cloudId;
175
- this.mcpUrl = opts.mcpUrl ?? MCP_URL;
176
- }
177
-
178
- /** The MCP session, with the auth scheme picked on first use. */
179
- private mcp(): Promise<McpClient> {
180
- this.mcpP ??= this.pickAuth().catch((e) => {
181
- this.mcpP = undefined;
182
- throw e;
183
- });
184
- return this.mcpP;
185
- }
186
-
187
- /** Which Authorization the MCP server honours for this token. A scoped token works only as Bearer; sent as
188
- * Basic the server still lists its tools but sees no site ("Cloud id … isn't explicitly granted"). So each
189
- * scheme is tried until getAccessibleAtlassianResources returns a site; a stored scheme is used as is. */
190
- private async pickAuth(): Promise<McpClient> {
191
- const make = (s: JiraAuth) => new McpClient(this.mcpUrl, { authorization: mcpAuth(this.creds, s) }, this.fetchFn);
192
- if (this.creds.auth) {
193
- this.picked = { scheme: this.creds.auth, verified: false };
194
- return make(this.creds.auth);
195
- }
196
- let fallback: { c: McpClient; scheme: JiraAuth } | undefined;
197
- let err: unknown;
198
- for (const scheme of ["bearer", "basic"] as const) {
199
- const c = make(scheme);
200
- try {
201
- const tools = await c.listTools();
202
- const t = tools.find((x) => (TOOLS.resources as readonly string[]).includes(x.name));
203
- if (!t) {
204
- // nothing to check with: the first scheme the server accepts
205
- this.picked = { scheme, verified: false };
206
- return c;
207
- }
208
- const r = await c.callTool(t.name, {});
209
- if (!r.isError && arr(resultValue(r), "resources").length) {
210
- this.picked = { scheme, verified: true };
211
- return c;
212
- }
213
- fallback ??= { c, scheme };
214
- } catch (e) {
215
- err ??= e;
216
- }
217
- }
218
- if (fallback) {
219
- this.picked = { scheme: fallback.scheme, verified: false };
220
- return fallback.c;
221
- }
222
- throw err;
223
- }
224
-
225
- /** The MCP auth scheme this client uses, after connecting; `verified` when it proved to reach a site. */
226
- async authScheme(): Promise<{ scheme: JiraAuth; verified: boolean }> {
227
- await this.mcp();
228
- return this.picked!;
164
+ this.mcp = new McpClient(opts.mcpUrl ?? MCP_URL, { authorization: bearer(creds) }, this.fetchFn, opts.mcp);
229
165
  }
230
166
 
231
167
  get site() {
@@ -236,7 +172,7 @@ export class JiraClient {
236
172
  }
237
173
 
238
174
  private async tool(op: Op): Promise<McpTool | undefined> {
239
- const tools = await (await this.mcp()).listTools();
175
+ const tools = await this.mcp.listTools();
240
176
  for (const n of TOOLS[op]) {
241
177
  const t = tools.find((x) => x.name === n);
242
178
  if (t) return t;
@@ -260,76 +196,55 @@ export class JiraClient {
260
196
  private async call(op: Op, logical: Record<string, unknown>): Promise<JiraResult<unknown>> {
261
197
  try {
262
198
  const t = await this.tool(op);
263
- 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) };
264
200
  const needsCloud = t.inputSchema?.properties && "cloudId" in t.inputSchema.properties;
265
201
  const args = this.args(t, { ...(needsCloud ? { cloudId: await this.cloudId() } : {}), ...logical });
266
- const r = await (await this.mcp()).callTool(t.name, args);
267
- if (r.isError) return { ok: false, error: `${t.name}: ${resultText(r).slice(0, 400)}` };
268
- 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) };
269
205
  } catch (e) {
270
- return { ok: false, error: (e as Error).message };
206
+ return { ok: false, error: explain((e as Error).message) };
271
207
  }
272
208
  }
273
209
 
274
- /** The site's cloudId: configured, else looked up among the token's accessible resources, else the site
275
- * 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. */
276
212
  cloudId(): Promise<string> {
277
213
  if (this.cloudIdFixed) return Promise.resolve(this.cloudIdFixed);
278
214
  this.cloudIdP ??= (async () => {
279
- try {
280
- const t = await this.tool("resources");
281
- if (t) {
282
- const r = await (await this.mcp()).callTool(t.name, {});
283
- const hit = arr(resultValue(r), "resources").map(rec).find((x) => str(x.url).replace(/^https?:\/\//, "").replace(/\/$/, "") === this.creds.site);
284
- if (hit?.cloudId ?? hit?.id) return str(hit.cloudId ?? hit.id);
285
- }
286
- } catch {
287
- /* fall through */
288
- }
289
- try {
290
- const res = await this.fetchFn(`https://${this.creds.site}/_edge/tenant_info`, { method: "GET", headers: {} });
291
- if (res.ok) {
292
- const id = str(rec(JSON.parse(await res.text())).cloudId);
293
- if (id) return id;
294
- }
295
- } catch {
296
- /* fall through */
297
- }
298
- return this.creds.site;
299
- })();
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
+ });
300
233
  return this.cloudIdP;
301
234
  }
302
235
 
303
- private async restBase(): Promise<string> {
304
- return this.gateway ?? `https://${this.creds.site}/rest/api/3`;
305
- }
306
-
307
- /** Jira REST with the same token (always Basic `email:token`, scoped or not) — only for what the MCP
308
- * server cannot do. */
309
- 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>> {
310
239
  try {
311
- const headers: Record<string, string> = { authorization: basicAuth(this.creds), accept: "application/json", ...extra };
312
- let payload: string | undefined;
313
- if (body !== undefined && typeof body === "string") payload = body;
314
- else if (body !== undefined) {
315
- headers["content-type"] = "application/json";
316
- payload = JSON.stringify(body);
317
- }
318
- let res = await this.fetchFn(`${await this.restBase()}${p}`, { method, headers, body: payload });
319
- if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
320
- // a scoped API token answers only through api.atlassian.com/ex/jira/<cloudId>
321
- const id = await this.cloudId();
322
- if (/^[0-9a-f-]{36}$/.test(id)) {
323
- this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
324
- res = await this.fetchFn(`${this.gateway}${p}`, { method, headers, body: payload });
325
- }
326
- }
327
- const text = await res.text();
328
- if (!res.ok) return { ok: false, error: `Jira REST ${method} ${p}: HTTP ${res.status} ${text.slice(0, 300)}` };
329
- 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("; ") };
330
244
  } catch (e) {
331
- return { ok: false, error: (e as Error).message };
245
+ return { ok: false, error: explain((e as Error).message) };
332
246
  }
247
+ return this.me();
333
248
  }
334
249
 
335
250
  async me(): Promise<JiraResult<JiraUser>> {
@@ -353,8 +268,7 @@ export class JiraClient {
353
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) };
354
269
  }
355
270
 
356
- /** The statuses of each issue type's workflow in a project. MCP `listJiraStatuses` when it answers per issue
357
- * 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"). */
358
272
  async statuses(project: string): Promise<JiraResult<Record<string, StatusInfo[]>>> {
359
273
  const toInfo = (s: Record<string, unknown>): StatusInfo => ({ name: str(s.name), category: str(rec(s.statusCategory).key ?? s.statusCategory ?? s.category) || undefined });
360
274
  const grouped = (v: unknown) => {
@@ -371,10 +285,9 @@ export class JiraClient {
371
285
  return Object.fromEntries(list.map((t) => [str(t.name), (t.statuses as unknown[]).map(rec).map(toInfo)]));
372
286
  };
373
287
  const m = await this.call("statuses", { mode: "project", project });
374
- if (m.ok && grouped(m.value)) return { ok: true, value: grouped(m.value)!, via: "mcp" };
375
- const r = await this.rest("GET", `/project/${encodeURIComponent(project)}/statuses`);
376
- if (r.ok && grouped(r.value)) return { ok: true, value: grouped(r.value)!, via: "rest" };
377
- 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)}` };
378
291
  }
379
292
 
380
293
  async issue(key: string): Promise<JiraResult<JiraIssue>> {
@@ -398,17 +311,25 @@ export class JiraClient {
398
311
  };
399
312
  }
400
313
 
314
+ /** The newest comments, newest first: pages of 20 (the server's cap) up to COMMENTS_MAX. */
401
315
  async comments(key: string): Promise<JiraResult<JiraComment[]>> {
402
316
  const toC = (c: Record<string, unknown>): JiraComment => {
403
317
  const a = rec(c.author);
404
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 };
405
319
  };
406
- // "full": the default compact view leaves out the author's accountId, which decides who answered (its page caps at 20)
407
- const m = await this.call("comments", { issue: key, max: 20, order: "-created", view: "full" });
408
- if (m.ok) return { ok: true, value: arr(m.value).map(rec).map(toC).filter((c) => c.id), via: "mcp" };
409
- const r = await this.rest("GET", `/issue/${encodeURIComponent(key)}/comment?orderBy=-created&maxResults=100`);
410
- if (r.ok) return { ok: true, value: arr(r.value).map(rec).map(toC).filter((c) => c.id), via: "rest" };
411
- 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) };
412
333
  }
413
334
 
414
335
  /** Post a comment (markdown); returns its id. */
@@ -416,79 +337,43 @@ export class JiraClient {
416
337
  const t = await this.tool("comment").catch(() => undefined);
417
338
  const takesFormat = !!t && Object.keys(t.inputSchema?.properties ?? {}).some((p) => ARGS.format.includes(p));
418
339
  const m = await this.call("comment", { issue: key, body: markdown, ...(takesFormat ? { format: "markdown" } : {}) });
419
- if (m.ok) {
420
- const v = rec(m.value);
421
- return { ok: true, value: str(v.commentId ?? v.id ?? rec(v.comment).id), via: "mcp" };
422
- }
423
- const r = await this.rest("POST", `/issue/${encodeURIComponent(key)}/comment`, { body: toAdf(markdown) });
424
- if (r.ok) return { ok: true, value: str(rec(r.value).id), via: "rest" };
425
- 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) };
426
343
  }
427
344
 
428
- /** v2's two-phase upload: phase 1 (filePath) mints a short-lived Atlassian Media upload — a curl command we
429
- * read but never run; we send the bytes ourselves; phase 2 (fileId) attaches the file to the issue. */
430
- private async uploadTwoPhase(key: string, file: string, data: Buffer): Promise<JiraResult<string>> {
431
- const p1 = await this.call("upload", { issue: key, filePath: path.resolve(file) });
432
- if (!p1.ok) return p1;
433
- const v = rec(p1.value);
434
- const req = parseUploadCommand(str(v.uploadCommand));
435
- if (!req) return { ok: false, error: "the upload step returned no Atlassian Media request dev-flow can send" };
436
- try {
437
- const res = await this.fetchFn(req.url, { method: "POST", headers: { ...req.headers, "content-type": mimeOf(file) }, body: data as unknown as string });
438
- const text = await res.text();
439
- if (!res.ok) return { ok: false, error: `Atlassian Media upload: HTTP ${res.status} ${text.slice(0, 200)}` };
440
- const j = rec(JSON.parse(text)); // rec() already unwraps { data: … }
441
- const fileId = str(j.id ?? rec(j.data).id);
442
- if (!fileId) return { ok: false, error: `Atlassian Media upload: no file id in ${text.slice(0, 200)}` };
443
- const p2 = await this.call("upload", { issue: key, fileId });
444
- return p2.ok ? { ok: true, value: path.basename(file), via: "mcp" } : p2;
445
- } catch (e) {
446
- return { ok: false, error: `Atlassian Media upload: ${(e as Error).message}` };
447
- }
448
- }
449
-
450
- /** 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. */
451
348
  async upload(key: string, file: string): Promise<JiraResult<string>> {
452
- const data = readFileSync(file);
453
349
  const name = path.basename(file);
454
- const t = await this.tool("upload").catch(() => undefined);
455
- const props = Object.keys(t?.inputSchema?.properties ?? {});
456
- let mcpError: string | undefined;
457
- if (t && props.includes("filePath") && props.includes("fileId")) {
458
- const r = await this.uploadTwoPhase(key, file, data);
459
- if (r.ok) return r;
460
- mcpError = r.error;
461
- }
462
- if (t && props.some((p) => ARGS.file.includes(p))) {
463
- const m = await this.call("upload", { issue: key, file: data.toString("base64"), filename: name, mime: mimeOf(file) });
464
- 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);
465
356
  }
466
- const boundary = `----devflow${Date.now().toString(16)}`;
467
- const head = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name.replace(/"/g, "")}"\r\nContent-Type: ${mimeOf(file)}\r\n\r\n`;
468
- 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");
469
361
  try {
470
- const send = async (base: string) =>
471
- this.fetchFn(`${base}/issue/${encodeURIComponent(key)}/attachments`, {
472
- method: "POST",
473
- headers: { authorization: basicAuth(this.creds), "x-atlassian-token": "no-check", "content-type": `multipart/form-data; boundary=${boundary}`, accept: "application/json" },
474
- // SAFETY: fetch accepts a Buffer body; FetchLike types it as string for the JSON paths
475
- body: body as unknown as string,
476
- });
477
- let res = await send(await this.restBase());
478
- if ((res.status === 401 || res.status === 403 || res.status === 404) && !this.gateway) {
479
- const id = await this.cloudId();
480
- if (/^[0-9a-f-]{36}$/.test(id)) {
481
- this.gateway = `https://api.atlassian.com/ex/jira/${id}/rest/api/3`;
482
- res = await send(this.gateway);
483
- }
484
- }
485
- if (!res.ok) {
486
- 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);
487
- return { ok: false, error: `attach ${name}: ${mcpError ? `${mcpError}; REST fallback: ` : ""}HTTP ${res.status} — ${why}` };
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;
488
367
  }
489
- 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);
490
375
  } catch (e) {
491
- return { ok: false, error: `attach ${name}: ${(e as Error).message}` };
376
+ return fail(`Atlassian Media upload: ${(e as Error).message}`);
492
377
  }
493
378
  }
494
379
 
@@ -501,11 +386,9 @@ export class JiraClient {
501
386
  const typeVal = types?.ok ? (types.value.find((x) => x.name.toLowerCase() === type.toLowerCase())?.id ?? type) : type;
502
387
  const takesFormat = props.some((p) => ARGS.format.includes(p));
503
388
  const m = await this.call("create", { project, issueType: typeVal, summary, description: description || undefined, ...(takesFormat && description ? { format: "markdown" } : {}) });
504
- const keyOf = (v: unknown) => str(rec(v).key ?? rec(rec(v).issue).key);
505
- if (m.ok && keyOf(m.value)) return { ok: true, value: keyOf(m.value), via: "mcp" };
506
- const r = await this.rest("POST", "/issue", { fields: { project: { key: project }, issuetype: { name: type }, summary, ...(description ? { description: toAdf(description) } : {}) } });
507
- if (r.ok && keyOf(r.value)) return { ok: true, value: keyOf(r.value), via: "rest" };
508
- 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)}` };
509
392
  }
510
393
 
511
394
  async transitions(key: string): Promise<JiraResult<{ id: string; name: string; to: string }[]>> {
package/src/jira/creds.ts CHANGED
@@ -1,26 +1,20 @@
1
1
  /**
2
- * Jira credentials — a Cloud API token for the Atlassian Rovo MCP server. A scoped token (the kind the MCP
3
- * server needs) is sent as `Authorization: Bearer <token>`; Basic `email:token` is the fallback for a plain
4
- * token. The scheme that worked is stored as `auth` next to the token, so later sessions skip the probe.
5
- * Jira's REST API always takes Basic `email:token`. They live outside the repo: `~/.pi/agent/dev-flow/jira.json` (mode 0600), written by
6
- * `/flow jira login`; `JIRA_EMAIL` / `JIRA_API_TOKEN` (and optionally `JIRA_SITE`) override the file.
7
- * 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.
8
9
  */
9
10
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
11
  import os from "node:os";
11
12
  import path from "node:path";
12
13
 
13
- /** How the token goes to the MCP server: `Bearer <token>` or Basic `email:token`. */
14
- export type JiraAuth = "bearer" | "basic";
15
- export const isJiraAuth = (v: unknown): v is JiraAuth => v === "bearer" || v === "basic";
16
-
17
14
  export interface JiraCreds {
18
15
  site: string; // acme.atlassian.net
19
- email: string;
20
16
  token: string;
21
17
  source: "env" | "file";
22
- /** the MCP auth scheme known to work; unset → probed (Bearer first) */
23
- auth?: JiraAuth;
24
18
  }
25
19
 
26
20
  export const credsPath = (home = os.homedir()) => path.join(process.env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent"), "dev-flow", "jira.json");
@@ -33,7 +27,7 @@ export const normSite = (s: string) =>
33
27
  .replace(/\/.*$/, "")
34
28
  .toLowerCase();
35
29
 
36
- type Store = { sites?: Record<string, { email: string; token: string; auth?: JiraAuth }> };
30
+ type Store = { sites?: Record<string, { token: string; [legacy: string]: unknown }> };
37
31
 
38
32
  function readStore(file: string): Store {
39
33
  try {
@@ -46,34 +40,20 @@ function readStore(file: string): Store {
46
40
  /** Credentials for `site` (or for the only/first stored site when none is named), or null. */
47
41
  export function loadCreds(site?: string, env: NodeJS.ProcessEnv = process.env, file = credsPath()): JiraCreds | null {
48
42
  const want = site ? normSite(site) : env.JIRA_SITE ? normSite(env.JIRA_SITE) : undefined;
49
- if (env.JIRA_EMAIL && env.JIRA_API_TOKEN && (want || env.JIRA_SITE))
50
- return { site: want ?? normSite(env.JIRA_SITE!), email: env.JIRA_EMAIL, token: env.JIRA_API_TOKEN, source: "env", ...(isJiraAuth(env.JIRA_AUTH) ? { auth: env.JIRA_AUTH } : {}) };
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" };
51
44
  const sites = readStore(file).sites ?? {};
52
45
  const key = want ?? Object.keys(sites)[0];
53
46
  const hit = key ? sites[key] : undefined;
54
- return hit && key ? { site: key, email: hit.email, token: hit.token, source: "file", ...(isJiraAuth(hit.auth) ? { auth: hit.auth } : {}) } : null;
47
+ return hit?.token && key ? { site: key, token: hit.token, source: "file" } : null;
55
48
  }
56
49
 
57
- export function saveCreds(site: string, email: string, token: string, file = credsPath(), auth?: JiraAuth): void {
50
+ export function saveCreds(site: string, token: string, file = credsPath()): void {
58
51
  mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
59
52
  const store = existsSync(file) ? readStore(file) : {};
60
- store.sites = { ...(store.sites ?? {}), [normSite(site)]: { email: email.trim(), token: token.trim(), ...(auth ? { auth } : {}) } };
61
- writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
62
- chmodSync(file, 0o600);
63
- }
64
-
65
- /** Remember the MCP auth scheme that worked for a stored login (no-op when the site or token changed). */
66
- export function saveAuth(creds: Pick<JiraCreds, "site" | "token">, auth: JiraAuth, file = credsPath()): void {
67
- if (!existsSync(file)) return;
68
- const store = readStore(file);
69
- const hit = store.sites?.[creds.site];
70
- if (!hit || hit.token !== creds.token || hit.auth === auth) return;
71
- hit.auth = auth;
53
+ store.sites = { ...(store.sites ?? {}), [normSite(site)]: { token: token.trim() } };
72
54
  writeFileSync(file, `${JSON.stringify(store, null, "\t")}\n`, { mode: 0o600 });
73
55
  chmodSync(file, 0o600);
74
56
  }
75
57
 
76
- export const basicAuth = (c: Pick<JiraCreds, "email" | "token">) => `Basic ${Buffer.from(`${c.email}:${c.token}`).toString("base64")}`;
77
-
78
- /** The MCP server's Authorization header for `scheme` (default: the stored one, else Bearer). */
79
- export const mcpAuth = (c: Pick<JiraCreds, "email" | "token" | "auth">, scheme: JiraAuth = c.auth ?? "bearer") => (scheme === "bearer" ? `Bearer ${c.token}` : basicAuth(c));
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 needs a scoped API token (read:jira:agent-interface, write:jira:agent-interface; sent as Bearer), and an org admin must have enabled API-token authentication for it (Atlassian Administration → Rovo MCP server). Check the token (/flow jira login re-enters it).`, 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;