@denvermullets/jait 1.5.0 → 1.6.0

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.
@@ -1,5 +1,6 @@
1
1
  import { readToken } from "./config-store.js";
2
2
  const DEFAULT_API_URL = "https://justanotherissuetracker.com";
3
+ const DEFAULT_TIMEOUT_MS = 30000;
3
4
  function getConfig() {
4
5
  const apiToken = process.env.MTASKS_API_TOKEN || readToken();
5
6
  if (!apiToken) {
@@ -13,6 +14,10 @@ function getConfig() {
13
14
  export function apiBaseUrl() {
14
15
  return (process.env.MTASKS_API_URL || DEFAULT_API_URL).replace(/\/$/, "");
15
16
  }
17
+ function apiTimeoutMs() {
18
+ const parsed = Number(process.env.MTASKS_API_TIMEOUT_MS);
19
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TIMEOUT_MS;
20
+ }
16
21
  export async function apiRequest(path, options = {}) {
17
22
  return (await apiRequestWithHeaders(path, options)).data;
18
23
  }
@@ -29,33 +34,53 @@ export async function apiRequestWithHeaders(path, options = {}) {
29
34
  }
30
35
  }
31
36
  }
32
- const response = await fetch(url.toString(), {
33
- method,
34
- headers: {
35
- Authorization: `Bearer ${token}`,
36
- Accept: "application/json",
37
- "Content-Type": "application/json",
38
- },
39
- body: body ? JSON.stringify(body) : undefined,
40
- });
41
- if (!response.ok) {
42
- const errorBody = await response.text();
43
- let message;
44
- try {
45
- const parsed = JSON.parse(errorBody);
46
- message =
47
- parsed.message || parsed.errors?.join(", ") || parsed.error || errorBody;
37
+ const timeoutMs = apiTimeoutMs();
38
+ const controller = new AbortController();
39
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
40
+ // The timer stays armed through the body read (a server can send headers
41
+ // and then stall) and is cleared only once the body is consumed.
42
+ try {
43
+ const response = await fetch(url.toString(), {
44
+ method,
45
+ headers: {
46
+ Authorization: `Bearer ${token}`,
47
+ Accept: "application/json",
48
+ "Content-Type": "application/json",
49
+ },
50
+ body: body ? JSON.stringify(body) : undefined,
51
+ signal: controller.signal,
52
+ });
53
+ if (!response.ok) {
54
+ const errorBody = await response.text();
55
+ let message;
56
+ try {
57
+ const parsed = JSON.parse(errorBody);
58
+ message =
59
+ parsed.message ||
60
+ parsed.errors?.join(", ") ||
61
+ parsed.error ||
62
+ errorBody;
63
+ }
64
+ catch {
65
+ message = errorBody;
66
+ }
67
+ throw new Error(`API error ${response.status}: ${message}`);
48
68
  }
49
- catch {
50
- message = errorBody;
69
+ // Some endpoints (e.g. a 204 No Content on DELETE) return an empty body.
70
+ // Guard against JSON.parse throwing "Unexpected end of JSON input".
71
+ const text = response.status === 204 ? "" : await response.text();
72
+ return {
73
+ data: (text ? JSON.parse(text) : undefined),
74
+ headers: response.headers,
75
+ };
76
+ }
77
+ catch (err) {
78
+ if (err instanceof Error && err.name === "AbortError") {
79
+ throw new Error(`Request to ${path} timed out after ${timeoutMs}ms`);
51
80
  }
52
- throw new Error(`API error ${response.status}: ${message}`);
81
+ throw err;
82
+ }
83
+ finally {
84
+ clearTimeout(timer);
53
85
  }
54
- // Some endpoints (e.g. a 204 No Content on DELETE) return an empty body.
55
- // Guard against JSON.parse throwing "Unexpected end of JSON input".
56
- const text = response.status === 204 ? "" : await response.text();
57
- return {
58
- data: (text ? JSON.parse(text) : undefined),
59
- headers: response.headers,
60
- };
61
86
  }
@@ -0,0 +1,44 @@
1
+ export interface SectionInfo {
2
+ heading: string;
3
+ level: number;
4
+ }
5
+ /** Base class for every expected splicing failure (bad heading, bad match). */
6
+ export declare class SectionError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ export declare class SectionNotFound extends SectionError {
10
+ constructor(heading: string, available: string[]);
11
+ }
12
+ export declare class DuplicateHeading extends SectionError {
13
+ constructor(heading: string, count: number);
14
+ }
15
+ export declare class TextNotFound extends SectionError {
16
+ constructor();
17
+ }
18
+ export declare class AmbiguousMatch extends SectionError {
19
+ constructor(count: number);
20
+ }
21
+ export declare class EmptyOldString extends SectionError {
22
+ constructor();
23
+ }
24
+ export declare function listSections(description: string): SectionInfo[];
25
+ /** Body of a section (heading line excluded), subsections included, verbatim. */
26
+ export declare function getSection(description: string, { heading }: {
27
+ heading: string;
28
+ }): string;
29
+ /** Replace a section's body (subsections included). Heading line is kept. */
30
+ export declare function replaceSection(description: string, { heading, body }: {
31
+ heading: string;
32
+ body: string;
33
+ }): string;
34
+ /** Append text at the end of a section (after its last subsection). */
35
+ export declare function appendToSection(description: string, { heading, text }: {
36
+ heading: string;
37
+ text: string;
38
+ }): string;
39
+ /** Literal find-and-replace over the whole description. */
40
+ export declare function replaceText(description: string, { oldString, newString, replaceAll, }: {
41
+ oldString: string;
42
+ newString: string;
43
+ replaceAll?: boolean;
44
+ }): string;
@@ -0,0 +1,156 @@
1
+ // Pure string-in, string-out helpers for reading and editing a markdown
2
+ // description by section. No API or MCP SDK imports on purpose.
3
+ /** Base class for every expected splicing failure (bad heading, bad match). */
4
+ export class SectionError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "SectionError";
8
+ }
9
+ }
10
+ export class SectionNotFound extends SectionError {
11
+ constructor(heading, available) {
12
+ super(`Section "${heading}" not found. Available headings: ${available.length ? available.map((h) => `"${h}"`).join(", ") : "(none)"}`);
13
+ this.name = "SectionNotFound";
14
+ }
15
+ }
16
+ export class DuplicateHeading extends SectionError {
17
+ constructor(heading, count) {
18
+ super(`Heading "${heading}" is ambiguous: it appears ${count} times in the description`);
19
+ this.name = "DuplicateHeading";
20
+ }
21
+ }
22
+ export class TextNotFound extends SectionError {
23
+ constructor() {
24
+ super("Text not found: found 0 matches for oldString");
25
+ this.name = "TextNotFound";
26
+ }
27
+ }
28
+ export class AmbiguousMatch extends SectionError {
29
+ constructor(count) {
30
+ super(`Ambiguous match: found ${count} matches for oldString; add surrounding context to make it unique or pass replaceAll`);
31
+ this.name = "AmbiguousMatch";
32
+ }
33
+ }
34
+ export class EmptyOldString extends SectionError {
35
+ constructor() {
36
+ super("oldString must not be empty");
37
+ this.name = "EmptyOldString";
38
+ }
39
+ }
40
+ const HEADING_RE = /^(#{2,6})\s+(.+)$/;
41
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
42
+ function parse(description) {
43
+ const lines = [];
44
+ const re = /([^\r\n]*)(\r\n|\n|$)/g;
45
+ let m;
46
+ while ((m = re.exec(description)) !== null) {
47
+ if (m[0] === "")
48
+ break;
49
+ lines.push({ text: m[1], eol: m[2] });
50
+ }
51
+ const headings = [];
52
+ let fence = null;
53
+ lines.forEach((line, index) => {
54
+ const f = FENCE_RE.exec(line.text);
55
+ if (fence) {
56
+ if (f &&
57
+ f[1][0] === fence[0] &&
58
+ f[1].length >= fence.length &&
59
+ line.text.trim() === f[1]) {
60
+ fence = null;
61
+ }
62
+ return;
63
+ }
64
+ if (f) {
65
+ fence = f[1];
66
+ return;
67
+ }
68
+ const h = HEADING_RE.exec(line.text);
69
+ if (!h)
70
+ return;
71
+ // CommonMark: an optional closing sequence of #s (preceded by whitespace)
72
+ // is not part of the heading text.
73
+ const heading = h[2]
74
+ .replace(/(?:^|\s+)#+\s*$/, "")
75
+ .trim();
76
+ if (heading)
77
+ headings.push({ index, heading, level: h[1].length });
78
+ });
79
+ return { lines, headings };
80
+ }
81
+ function locate(description, heading) {
82
+ const { lines, headings } = parse(description);
83
+ const matches = headings.filter((h) => h.heading === heading);
84
+ if (matches.length === 0) {
85
+ throw new SectionNotFound(heading, headings.map((h) => h.heading));
86
+ }
87
+ if (matches.length > 1)
88
+ throw new DuplicateHeading(heading, matches.length);
89
+ const target = matches[0];
90
+ const next = headings.find((h) => h.index > target.index && h.level <= target.level);
91
+ const end = next ? next.index : lines.length;
92
+ const join = (from, to) => lines
93
+ .slice(from, to)
94
+ .map((l) => l.text + l.eol)
95
+ .join("");
96
+ const eol = lines.find((l) => l.eol)?.eol || "\n";
97
+ return {
98
+ head: lines[target.index],
99
+ body: join(target.index + 1, end),
100
+ before: join(0, target.index + 1),
101
+ after: join(end, lines.length),
102
+ hasAfter: end < lines.length,
103
+ eol,
104
+ };
105
+ }
106
+ function splitTrailingBreaks(s) {
107
+ const m = /(?:\r?\n)*$/.exec(s);
108
+ return { content: s.slice(0, m.index), trailing: m[0] };
109
+ }
110
+ function assemble(loc, content, trailing) {
111
+ let before = loc.before;
112
+ if (content && !loc.head.eol)
113
+ before += loc.eol; // heading was the last, unterminated line
114
+ let body = content + trailing;
115
+ if (loc.hasAfter && body && !/\n$/.test(body))
116
+ body += loc.eol;
117
+ if (loc.hasAfter && !body && !loc.head.eol)
118
+ before += loc.eol;
119
+ return before + body + loc.after;
120
+ }
121
+ export function listSections(description) {
122
+ return parse(description).headings.map(({ heading, level }) => ({
123
+ heading,
124
+ level,
125
+ }));
126
+ }
127
+ /** Body of a section (heading line excluded), subsections included, verbatim. */
128
+ export function getSection(description, { heading }) {
129
+ return locate(description, heading).body;
130
+ }
131
+ /** Replace a section's body (subsections included). Heading line is kept. */
132
+ export function replaceSection(description, { heading, body }) {
133
+ const loc = locate(description, heading);
134
+ const { trailing } = splitTrailingBreaks(loc.body);
135
+ return assemble(loc, splitTrailingBreaks(body).content, trailing);
136
+ }
137
+ /** Append text at the end of a section (after its last subsection). */
138
+ export function appendToSection(description, { heading, text }) {
139
+ const loc = locate(description, heading);
140
+ const { content, trailing } = splitTrailingBreaks(loc.body);
141
+ const add = splitTrailingBreaks(text).content;
142
+ const joined = content ? content + loc.eol + add : add;
143
+ return assemble(loc, joined, trailing);
144
+ }
145
+ /** Literal find-and-replace over the whole description. */
146
+ export function replaceText(description, { oldString, newString, replaceAll = false, }) {
147
+ if (oldString === "")
148
+ throw new EmptyOldString();
149
+ const parts = description.split(oldString);
150
+ const count = parts.length - 1;
151
+ if (count === 0)
152
+ throw new TextNotFound();
153
+ if (count > 1 && !replaceAll)
154
+ throw new AmbiguousMatch(count);
155
+ return parts.join(newString);
156
+ }
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ interface DescribedResource {
4
+ description?: string | null;
5
+ }
6
+ interface SectionToolConfig<R extends DescribedResource> {
7
+ noun: "issue" | "project";
8
+ /** Zod shape for the ids that address one resource. */
9
+ idShape: z.ZodRawShape;
10
+ /** API path of the resource, from the tool args. */
11
+ path: (args: any) => string;
12
+ /** Key the PATCH body is nested under. */
13
+ bodyKey: string;
14
+ /** Resource identifier used in confirmations, from the PATCH response. */
15
+ label: (resource: R, args: any) => string;
16
+ }
17
+ export declare function registerDescriptionSectionTools<R extends DescribedResource>(server: McpServer, cfg: SectionToolConfig<R>): void;
18
+ export {};
@@ -0,0 +1,77 @@
1
+ import { z } from "zod";
2
+ import { apiRequest } from "../api-client.js";
3
+ import { SectionError, appendToSection, getSection, listSections, replaceSection, replaceText, } from "../description-sections.js";
4
+ const textResult = (text) => ({
5
+ content: [{ type: "text", text }],
6
+ });
7
+ // Splicer failures are expected: show the message to the agent as an error
8
+ // result. Anything else (network, auth) propagates.
9
+ function sectionErrorResult(err) {
10
+ if (err instanceof SectionError) {
11
+ return { ...textResult(err.message), isError: true };
12
+ }
13
+ throw err;
14
+ }
15
+ const headingArg = z
16
+ .string()
17
+ .describe('Exact heading text without the leading #s, e.g. "Goals"');
18
+ export function registerDescriptionSectionTools(server, cfg) {
19
+ const { noun, idShape, path, bodyKey, label } = cfg;
20
+ const upper = noun[0].toUpperCase() + noun.slice(1);
21
+ const note = ` Use this instead of update_${noun} for partial description edits.`;
22
+ const fetchDescription = async (args) => (await apiRequest(path(args))).description ?? "";
23
+ // Fetch, splice, PATCH. Returns a short confirmation, never the description.
24
+ const edit = async (args, splice, confirmation) => {
25
+ try {
26
+ const updated = splice(await fetchDescription(args));
27
+ const saved = await apiRequest(path(args), {
28
+ method: "PATCH",
29
+ body: { [bodyKey]: { description: updated } },
30
+ });
31
+ return textResult(confirmation(label(saved, args)));
32
+ }
33
+ catch (err) {
34
+ return sectionErrorResult(err);
35
+ }
36
+ };
37
+ server.tool(`list_${noun}_sections`, `List the headings (with levels) in ${noun === "issue" ? "an issue" : "a project"}'s description. Start here to see what sections exist before reading or editing one.`, idShape, async (args) => {
38
+ const sections = listSections(await fetchDescription(args));
39
+ return textResult(sections.length
40
+ ? sections.map((s) => `${"#".repeat(s.level)} ${s.heading}`).join("\n")
41
+ : "No sections found.");
42
+ });
43
+ server.tool(`get_${noun}_section`, `Read one section of ${noun === "issue" ? "an issue" : "a project"}'s description (heading excluded, subsections included) without loading the whole description. Use this instead of get_${noun} when you only need one section.`, { ...idShape, heading: headingArg }, async (args) => {
44
+ try {
45
+ const body = getSection(await fetchDescription(args), {
46
+ heading: args.heading,
47
+ });
48
+ return textResult(body || "(empty section)");
49
+ }
50
+ catch (err) {
51
+ return sectionErrorResult(err);
52
+ }
53
+ });
54
+ server.tool(`replace_${noun}_section`, `Replace the body of one section of ${noun === "issue" ? "an issue" : "a project"}'s description, keeping its heading. Use when rewriting most of a section; to add to the end use append_to_${noun}_section, for small tweaks use edit_${noun}_description.${note}`, {
55
+ ...idShape,
56
+ heading: headingArg,
57
+ body: z.string().describe("New section body in markdown (heading not included)"),
58
+ }, async (args) => edit(args, (d) => replaceSection(d, { heading: args.heading, body: args.body }), (id) => `Replaced section "${args.heading}" in ${id}.`));
59
+ server.tool(`append_to_${noun}_section`, `Append text to the end of one section of ${noun === "issue" ? "an issue" : "a project"}'s description. Use when adding to a section without touching what is there; to rewrite it use replace_${noun}_section.${note}`, {
60
+ ...idShape,
61
+ heading: headingArg,
62
+ text: z.string().describe("Markdown text to append"),
63
+ }, async (args) => edit(args, (d) => appendToSection(d, { heading: args.heading, text: args.text }), (id) => `Appended to section "${args.heading}" in ${id}.`));
64
+ server.tool(`edit_${noun}_description`, `Find-and-replace literal text in ${noun === "issue" ? "an issue" : "a project"}'s description. Use for small edits inside a section (a word, a line, a checkbox); fails if old_string is not found or matches more than once unless replace_all is true.${note}`, {
65
+ ...idShape,
66
+ old_string: z.string().describe("Exact text to find"),
67
+ new_string: z.string().describe("Replacement text"),
68
+ replace_all: z
69
+ .boolean()
70
+ .optional()
71
+ .describe("Replace every match instead of requiring exactly one"),
72
+ }, async (args) => edit(args, (d) => replaceText(d, {
73
+ oldString: args.old_string,
74
+ newString: args.new_string,
75
+ replaceAll: args.replace_all,
76
+ }), (id) => `Edited description of ${id}.`));
77
+ }
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { apiRequest, apiRequestWithHeaders } from "../api-client.js";
3
3
  import { attachUploads, filePathsSchema, formatAttachments, uploadLocalFiles, } from "../attachments.js";
4
+ import { registerDescriptionSectionTools } from "./description-section-tools.js";
4
5
  const priorityEnum = z
5
6
  .enum(["urgent", "high", "medium", "low", "no_priority"])
6
7
  .describe("Issue priority");
@@ -102,6 +103,16 @@ export function formatActivityPage(entries, nextBeforeId) {
102
103
  return lines.join("\n");
103
104
  }
104
105
  export function registerIssueTools(server) {
106
+ registerDescriptionSectionTools(server, {
107
+ noun: "issue",
108
+ idShape: {
109
+ team_id: z.number().describe("Team ID"),
110
+ issue_id: z.number().describe("Issue ID"),
111
+ },
112
+ path: ({ team_id, issue_id }) => `/api/v1/teams/${team_id}/issues/${issue_id}`,
113
+ bodyKey: "issue",
114
+ label: (issue) => issue.identifier,
115
+ });
105
116
  server.tool("list_issues", "List issues for a team, with optional filters", {
106
117
  team_id: z.number().describe("Team ID"),
107
118
  lane_id: z.number().optional().describe("Filter by status lane ID"),
@@ -127,7 +138,7 @@ export function registerIssueTools(server) {
127
138
  content: [{ type: "text", text: text || "No issues found." }],
128
139
  };
129
140
  });
130
- server.tool("get_issue", "Get full details of a specific issue", {
141
+ server.tool("get_issue", "Get full details of a specific issue. For a long description, use list_issue_sections and get_issue_section to read just part of it.", {
131
142
  team_id: z.number().describe("Team ID"),
132
143
  issue_id: z.number().describe("Issue ID"),
133
144
  }, async ({ team_id, issue_id }) => {
@@ -224,11 +235,14 @@ export function registerIssueTools(server) {
224
235
  ],
225
236
  };
226
237
  });
227
- server.tool("update_issue", "Update an existing issue (change priority, reassign, move lane, etc.)", {
238
+ server.tool("update_issue", "Update an existing issue (change priority, reassign, move lane, etc.). For partial description edits prefer edit_issue_description (small edits), replace_issue_section (rewriting a section) or append_to_issue_section (adding text).", {
228
239
  team_id: z.number().describe("Team ID"),
229
240
  issue_id: z.number().describe("Issue ID"),
230
241
  title: z.string().optional().describe("New title"),
231
- description: z.string().optional().describe("New description"),
242
+ description: z
243
+ .string()
244
+ .optional()
245
+ .describe("New description. Use only for a full rewrite or when seeding a new description; for partial edits use edit_issue_description, replace_issue_section or append_to_issue_section"),
232
246
  priority: priorityEnum.optional(),
233
247
  lane_id: z.number().optional().describe("Move to lane ID"),
234
248
  assignee_id: z.number().optional().describe("Reassign to user ID"),
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { apiRequest, apiRequestWithHeaders } from "../api-client.js";
3
3
  import { attachUploads, filePathsSchema, formatAttachments, uploadLocalFiles, } from "../attachments.js";
4
+ import { registerDescriptionSectionTools } from "./description-section-tools.js";
4
5
  import { formatActivityPage } from "./issues.js";
5
6
  const projectStatusEnum = z
6
7
  .enum(["backlog", "started", "paused", "completed", "cancelled"])
@@ -46,7 +47,7 @@ export function registerProjectTools(server) {
46
47
  content: [{ type: "text", text: text || "No projects found." }],
47
48
  };
48
49
  });
49
- server.tool("get_project", "Get full details of a specific project", {
50
+ server.tool("get_project", "Get full details of a specific project. For a long description, use list_project_sections and get_project_section to read just part of it.", {
50
51
  team_id: z.number().describe("Team ID"),
51
52
  project_id: z.number().describe("Project ID"),
52
53
  }, async ({ team_id, project_id }) => {
@@ -98,11 +99,14 @@ export function registerProjectTools(server) {
98
99
  ],
99
100
  };
100
101
  });
101
- server.tool("update_project", "Update an existing project (change status, priority, lead, dates, etc.)", {
102
+ server.tool("update_project", "Update an existing project (change status, priority, lead, dates, etc.). For partial description edits prefer edit_project_description (small edits), replace_project_section (rewriting a section) or append_to_project_section (adding text).", {
102
103
  team_id: z.number().describe("Team ID"),
103
104
  project_id: z.number().describe("Project ID"),
104
105
  name: z.string().optional().describe("New name"),
105
- description: z.string().optional().describe("New description"),
106
+ description: z
107
+ .string()
108
+ .optional()
109
+ .describe("New description. Use only for a full rewrite or when seeding a new description; for partial edits use edit_project_description, replace_project_section or append_to_project_section"),
106
110
  status: projectStatusEnum.optional(),
107
111
  priority: priorityEnum.optional(),
108
112
  lead_id: z.number().optional().describe("New lead user ID"),
@@ -217,4 +221,14 @@ export function registerProjectTools(server) {
217
221
  ],
218
222
  };
219
223
  });
224
+ registerDescriptionSectionTools(server, {
225
+ noun: "project",
226
+ idShape: {
227
+ team_id: z.number().describe("Team ID"),
228
+ project_id: z.number().describe("Project ID"),
229
+ },
230
+ path: ({ team_id, project_id }) => `/api/v1/teams/${team_id}/projects/${project_id}`,
231
+ bodyKey: "project",
232
+ label: (project) => `project "${project.name}"`,
233
+ });
220
234
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@denvermullets/jait",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "MCP server for Just Another Issue Tracker",
5
5
  "type": "module",
6
6
  "bin": {