@uarlouski/testrail-mcp-server 3.2.0 → 3.3.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.
package/README.md CHANGED
@@ -17,6 +17,7 @@
17
17
  <a href="https://github.com/uarlouski/testrail-mcp-server"><img src="https://img.shields.io/github/stars/uarlouski/testrail-mcp-server.svg?style=social&label=Star" alt="GitHub stars"></a>
18
18
  <a href="https://glama.ai/mcp/servers/uarlouski/testrail-mcp-server"><img src="https://glama.ai/mcp/servers/uarlouski/testrail-mcp-server/badges/score.svg" alt="Score Badge"></a>
19
19
  <a href="https://m8ven.ai/mcp/uarlouski/testrail-mcp-server"><img src="https://m8ven.ai/badge/mcp/uarlouski/testrail-mcp-server" alt="M8ven Score"></a>
20
+ <a href="https://smithery.ai/servers/uarlouski/testrail-mcp-server"><img src="https://smithery.ai/badge/uarlouski/testrail-mcp-server" alt="Smithery badge"></a>
20
21
  </p>
21
22
 
22
23
  <p align="center">
@@ -6,6 +6,8 @@ import { resolveCustomFieldValue } from "../../utils/mapper.js";
6
6
  import { getBaseDirectory } from "../../utils/fs.js";
7
7
  import { CaseFieldTypeId, getFieldType } from "./fields.js";
8
8
  import { fetchFilteredCases } from "./get_cases.js";
9
+ import { createSectionLookup, formatSectionPath, resolveSectionPath } from "../../utils/section_path.js";
10
+ import { computeContentHash } from "../../utils/content_hash.js";
9
11
  const parameters = {
10
12
  case_ids: z.array(z.union([z.string(), z.number()])).optional().describe("List of test case IDs (e.g. ['C123', 456]). Provide either case_ids OR project_id."),
11
13
  project_id: z.number().optional().describe("The ID of the project to export cases from. Required if case_ids is not provided."),
@@ -13,7 +15,7 @@ const parameters = {
13
15
  filter: z.record(z.string(), z.string()).optional().describe("Optional API-side filters (e.g. priority_id, type_id, milestone_id, refs, created_after, etc.)."),
14
16
  where: z.record(z.string(), z.any()).optional().describe("Optional client-side filter for any field including custom fields (filters after fetching cases). Supports exact value matching. Example: {\"custom_automation_status\": 1}"),
15
17
  output_dir: z.string().optional().describe("Directory to save exported files. Defaults to an auto-generated directory in the current working directory."),
16
- ignored_fields: z.array(z.string()).optional().describe("Optional list of custom field names or system names to ignore/exclude from export (e.g. ['custom_review_status', 'review_status']). Supports both full system_name and stripped field names. Core metadata attributes (case_id, updated_on, title, section, priority, references, labels) cannot be ignored."),
18
+ ignored_fields: z.array(z.string()).optional().describe("Optional list of custom field names or system names to ignore/exclude from export (e.g. ['custom_review_status', 'review_status']). Supports both full system_name and stripped field names. Core metadata attributes (case_id, updated_on, title, section, section_path, priority, references, labels, content_hash) cannot be ignored."),
17
19
  };
18
20
  function formatStepsSeparated(steps) {
19
21
  return steps.map((step, idx) => {
@@ -105,11 +107,11 @@ function categorizeCustomFields(testCase, applicableFieldDefs, ignoredFieldsSet)
105
107
  }
106
108
  return { markdownFields, metadataFields };
107
109
  }
108
- function buildMarkdownBody(testCase, sectionName, markdownFields) {
110
+ function buildMarkdownBody(testCase, sectionPath, markdownFields) {
109
111
  const mdLines = [];
110
112
  mdLines.push(`# [C${testCase.id}] ${sanitizeValue(testCase.title)}`);
111
113
  mdLines.push("");
112
- mdLines.push(`**Section**: ${sectionName}`);
114
+ mdLines.push(`**Section**: ${sectionPath.length > 0 ? formatSectionPath(sectionPath) : "Unknown"}`);
113
115
  mdLines.push("");
114
116
  for (const { header, value, fieldDef } of markdownFields) {
115
117
  mdLines.push(`## ${header}`);
@@ -123,27 +125,44 @@ function buildMarkdownBody(testCase, sectionName, markdownFields) {
123
125
  }
124
126
  return mdLines.join("\n").trim() + "\n";
125
127
  }
126
- function buildMetadataAttributes(testCase, sectionName, priority, metadataFields) {
128
+ function buildMetadataAttributes(testCase, sectionPath, priority, metadataFields) {
127
129
  const metadataAttributes = {
128
130
  case_id: testCase.id,
129
131
  updated_on: testCase.updated_on,
130
132
  title: testCase.title,
131
- section: sectionName,
133
+ section: sectionPath.length > 0 ? sectionPath[sectionPath.length - 1] : "Unknown",
132
134
  priority: priority,
133
135
  };
136
+ if (sectionPath.length > 0) {
137
+ metadataAttributes.section_path = sectionPath;
138
+ }
134
139
  if (testCase.refs) {
135
140
  metadataAttributes.references = testCase.refs;
136
141
  }
137
142
  if (testCase.labels && testCase.labels.length > 0) {
138
143
  metadataAttributes.labels = testCase.labels.map(l => l.title);
139
144
  }
145
+ const CORE_METADATA_KEYS = new Set([
146
+ "case_id",
147
+ "updated_on",
148
+ "title",
149
+ "section",
150
+ "section_path",
151
+ "priority",
152
+ "references",
153
+ "labels",
154
+ "content_hash",
155
+ ]);
140
156
  for (const { key, value, fieldDef } of metadataFields) {
157
+ const targetKey = CORE_METADATA_KEYS.has(key)
158
+ ? (fieldDef?.system_name || `custom_${key}`)
159
+ : key;
141
160
  if (fieldDef?.type_id === CaseFieldTypeId.MultiSelect) {
142
161
  const listVal = Array.isArray(value) ? value : [value];
143
- metadataAttributes[key] = sanitizeMetadataValue(listVal.map(item => String(item)));
162
+ metadataAttributes[targetKey] = sanitizeMetadataValue(listVal.map(item => String(item)));
144
163
  }
145
164
  else {
146
- metadataAttributes[key] = sanitizeMetadataValue(value);
165
+ metadataAttributes[targetKey] = sanitizeMetadataValue(value);
147
166
  }
148
167
  }
149
168
  return metadataAttributes;
@@ -195,21 +214,23 @@ export const exportCasesForRagTool = {
195
214
  }
196
215
  }
197
216
  }
217
+ let preloadedSections = [];
218
+ if (testCases.length > 0) {
219
+ preloadedSections = await client.getSections(project_id, suite_id).catch(() => []);
220
+ }
221
+ const sectionLookup = createSectionLookup(client, preloadedSections);
198
222
  const writtenFiles = [];
199
223
  for (const testCase of testCases) {
200
- let sectionName = "Unknown";
201
- if (testCase.section_id) {
202
- const section = await client.getSection(Number(testCase.section_id)).catch(() => null);
203
- if (section?.name) {
204
- sectionName = section.name;
205
- }
206
- }
224
+ const sectionPath = testCase.section_id
225
+ ? await resolveSectionPath(Number(testCase.section_id), sectionLookup)
226
+ : [];
207
227
  const priority = priorities.find(p => p.id === testCase.priority_id)?.name || "Unknown";
208
228
  const templateId = testCase.template_id;
209
229
  const applicableFields = caseFields.filter(field => field.include_all || (templateId !== null && templateId !== undefined && field.template_ids.includes(templateId)));
210
230
  const { markdownFields, metadataFields } = categorizeCustomFields(testCase, applicableFields, ignoredFieldsSet);
211
- const markdownContent = buildMarkdownBody(testCase, sectionName, markdownFields);
212
- const metadataAttributes = buildMetadataAttributes(testCase, sectionName, priority, metadataFields);
231
+ const markdownContent = buildMarkdownBody(testCase, sectionPath, markdownFields);
232
+ const metadataAttributes = buildMetadataAttributes(testCase, sectionPath, priority, metadataFields);
233
+ metadataAttributes.content_hash = computeContentHash(markdownContent, metadataAttributes);
213
234
  const docFilename = `C${testCase.id}.md`;
214
235
  const metaFilename = `C${testCase.id}.md.metadata.json`;
215
236
  await fs.promises.writeFile(path.join(targetDir, docFilename), markdownContent, "utf-8");
@@ -55,3 +55,13 @@ export const READONLY_CASE_FIELDS = [
55
55
  "estimate_forecast",
56
56
  "is_deleted",
57
57
  ];
58
+ /**
59
+ * Standard case property names that must not be overwritten by custom fields.
60
+ * If a custom field's converted label collides with one of these names (e.g. "labels", "title"),
61
+ * the custom field retains its `system_name` (e.g. `custom_labels`, `custom_title`) to prevent collisions.
62
+ */
63
+ export const RESERVED_CASE_FIELDS = new Set([
64
+ ...SYSTEM_FIELDS.map(f => f.label.toLowerCase()),
65
+ ...SYSTEM_FIELDS.map(f => f.system_name),
66
+ ...READONLY_CASE_FIELDS,
67
+ ]);
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { processCustomFields } from "../../utils/mapper.js";
3
3
  import { normalizeEntityId } from "../../utils/sanitizer.js";
4
- import { LabelSchema } from "../commons/types.js";
4
+ import { CaseLabelSchema } from "../commons/types.js";
5
5
  const parameters = {
6
6
  case_id: z.string().describe("The ID of the test case (e.g. '123' or 'C123')"),
7
7
  };
@@ -23,15 +23,15 @@ export const getCaseTool = {
23
23
  const priority = priorities.find(p => p.id === testCase.priority_id);
24
24
  const customFields = processCustomFields(testCase, caseFields);
25
25
  const response = {
26
+ ...customFields,
26
27
  id: testCase.id,
27
28
  title: testCase.title,
28
29
  section: section.name,
29
30
  type: caseType ? caseType.name : "Unknown",
30
31
  priority: priority ? priority.name : "Unknown",
31
- labels: (testCase.labels || []).map((label) => LabelSchema.parse(label)),
32
+ labels: (testCase.labels || []).map((label) => CaseLabelSchema.parse(label)),
32
33
  references: testCase.refs,
33
34
  updated_on: testCase.updated_on,
34
- ...customFields
35
35
  };
36
36
  return response;
37
37
  }
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { LabelSchema } from "../commons/types.js";
2
+ import { CaseLabelSchema } from "../commons/types.js";
3
3
  import { CaseFieldTypeId } from "./fields.js";
4
4
  export { CaseFieldTypeId };
5
5
  export const CaseFieldConfigSchema = z.object({
@@ -42,7 +42,7 @@ export const CaseSchema = z.object({
42
42
  estimate_forecast: z.string().nullable().optional(),
43
43
  suite_id: z.number(),
44
44
  is_deleted: z.number().optional(),
45
- labels: z.array(LabelSchema),
45
+ labels: z.array(CaseLabelSchema),
46
46
  }).loose();
47
47
  export const CaseHistoryChangeSchema = z.object({
48
48
  field: z.string(),
@@ -6,7 +6,7 @@ const parameters = {
6
6
  export const getLabelsTool = {
7
7
  name: "get_labels",
8
8
  mode: "read",
9
- description: "Get all available test case labels (sometimes called tags) for a project. Returns label IDs and titles that can be used when creating or updating test cases.",
9
+ description: "Get all available test case labels (sometimes called tags) for a project. Returns label IDs and names that can be used when creating or updating test cases.",
10
10
  parameters,
11
11
  handler: async ({ project_id }, client) => {
12
12
  const labels = await client.getLabels(project_id);
@@ -1,5 +1,11 @@
1
1
  import { z } from "zod";
2
+ /** Label as returned by the `get_labels` endpoint (uses `name`). */
2
3
  export const LabelSchema = z.object({
4
+ id: z.number(),
5
+ name: z.string(),
6
+ });
7
+ /** Label as embedded in a case payload (`get_case`, `get_cases`); uses `title`. */
8
+ export const CaseLabelSchema = z.object({
3
9
  id: z.number(),
4
10
  title: z.string(),
5
11
  });
@@ -0,0 +1,47 @@
1
+ import * as crypto from "crypto";
2
+ export const DEFAULT_VOLATILE_KEYS = new Set([
3
+ "content_hash",
4
+ "export_time",
5
+ "exported_at",
6
+ "output_path",
7
+ "output_dir",
8
+ ]);
9
+ /**
10
+ * Serializes a value to canonical JSON with sorted object keys,
11
+ * normalized \n line endings, and volatile keys omitted.
12
+ */
13
+ export function canonicalizeJson(val, volatileKeys = DEFAULT_VOLATILE_KEYS) {
14
+ if (val === undefined) {
15
+ return "null";
16
+ }
17
+ if (val === null || typeof val !== "object") {
18
+ if (typeof val === "string") {
19
+ return JSON.stringify(val.replace(/\r\n/g, "\n"));
20
+ }
21
+ return JSON.stringify(val);
22
+ }
23
+ if (Array.isArray(val)) {
24
+ return "[" + val.map(item => canonicalizeJson(item, volatileKeys)).join(",") + "]";
25
+ }
26
+ const sortedKeys = Object.keys(val)
27
+ .filter(key => !volatileKeys.has(key) && val[key] !== undefined)
28
+ .sort();
29
+ const entries = sortedKeys.map(key => {
30
+ return JSON.stringify(key) + ":" + canonicalizeJson(val[key], volatileKeys);
31
+ });
32
+ return "{" + entries.join(",") + "}";
33
+ }
34
+ /**
35
+ * Computes a deterministic SHA-256 content hash of the exported Markdown body
36
+ * and its companion metadataAttributes (excluding content_hash and volatile keys).
37
+ *
38
+ * Formula: sha256( markdown body + "\n" + canonical JSON of metadataAttributes, excluding content_hash )
39
+ * Format: "sha256:<hex>"
40
+ */
41
+ export function computeContentHash(markdownBody, metadataAttributes, volatileKeys = DEFAULT_VOLATILE_KEYS) {
42
+ const normalizedMarkdown = markdownBody.replace(/\r\n/g, "\n");
43
+ const canonicalJson = canonicalizeJson(metadataAttributes, volatileKeys);
44
+ const hashInput = `${normalizedMarkdown}\n${canonicalJson}`;
45
+ const digest = crypto.createHash("sha256").update(hashInput, "utf-8").digest("hex");
46
+ return `sha256:${digest}`;
47
+ }
@@ -1,5 +1,7 @@
1
1
  import { CaseFieldTypeId } from "../tools/cases/types.js";
2
+ import { RESERVED_CASE_FIELDS } from "../tools/cases/fields.js";
2
3
  import { sanitizeValue } from "./sanitizer.js";
4
+ export { RESERVED_CASE_FIELDS };
3
5
  /**
4
6
  * Processes custom fields from a test case, converting system names to human-readable labels
5
7
  * and mapping dropdown values to their display text.
@@ -14,7 +16,9 @@ export function processCustomFields(testCase, caseFields) {
14
16
  const fieldNameMap = new Map();
15
17
  const dropdownOptionsMap = new Map();
16
18
  for (const field of applicableFields) {
17
- fieldNameMap.set(field.system_name, toSnakeCase(field.label));
19
+ const snakeLabel = toSnakeCase(field.label);
20
+ const outputKey = RESERVED_CASE_FIELDS.has(snakeLabel) ? field.system_name : snakeLabel;
21
+ fieldNameMap.set(field.system_name, outputKey);
18
22
  const optionsMap = parseDropdownOptions(field);
19
23
  if (optionsMap.size > 0) {
20
24
  dropdownOptionsMap.set(field.system_name, optionsMap);
@@ -12,6 +12,31 @@ function decodeHtmlEntities(str) {
12
12
  .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code)))
13
13
  .replace(/&#x([0-9a-fA-F]+);/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
14
14
  }
15
+ const KNOWN_HTML_TAGS = new Set([
16
+ 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio',
17
+ 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button',
18
+ 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup',
19
+ 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt',
20
+ 'em', 'embed',
21
+ 'fieldset', 'figcaption', 'figure', 'footer', 'form',
22
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html',
23
+ 'i', 'iframe', 'img', 'input', 'ins',
24
+ 'kbd',
25
+ 'label', 'legend', 'li', 'link',
26
+ 'main', 'map', 'mark', 'menu', 'meta', 'meter',
27
+ 'nav', 'noscript',
28
+ 'object', 'ol', 'optgroup', 'option', 'output',
29
+ 'p', 'picture', 'pre', 'progress',
30
+ 'q',
31
+ 'rp', 'rt', 'ruby',
32
+ 's', 'samp', 'script', 'search', 'section', 'select', 'slot', 'small', 'source', 'span', 'strong', 'style', 'sub',
33
+ 'summary', 'sup', 'svg',
34
+ 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track',
35
+ 'u', 'ul',
36
+ 'var', 'video',
37
+ 'wbr',
38
+ 'font', 'center', 'strike', 'tt', 'big', 'marquee', 'nobr', 'o:p'
39
+ ]);
15
40
  /**
16
41
  * Converts TestRail HTML markup to clean, structured Markdown / plain text.
17
42
  */
@@ -78,8 +103,20 @@ export function htmlToMarkdown(html) {
78
103
  });
79
104
  return `\n${items}\n`;
80
105
  });
81
- // Strip remaining HTML tags
82
- text = text.replace(/<[^>]+>/g, '');
106
+ // Strip scripts and styles along with their content
107
+ text = text.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '');
108
+ text = text.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '');
109
+ // Strip HTML comments, CDATA, and DOCTYPE declarations
110
+ text = text.replace(/<!--[\s\S]*?-->/g, '');
111
+ text = text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/gi, '$1');
112
+ text = text.replace(/<!DOCTYPE[^>]*>/gi, '');
113
+ // Strip remaining known HTML tags while preserving comparison signs and non-HTML angle brackets
114
+ text = text.replace(/<\/?([a-zA-Z][a-zA-Z0-9:-]*)(?:\s+[a-zA-Z_:@][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*\s*\/?>/gi, (match, tagName) => {
115
+ if (KNOWN_HTML_TAGS.has(tagName.toLowerCase())) {
116
+ return '';
117
+ }
118
+ return match;
119
+ });
83
120
  // Decode HTML entities
84
121
  text = decodeHtmlEntities(text);
85
122
  // Clean up whitespace and newlines
@@ -0,0 +1,60 @@
1
+ export const SECTION_PATH_SEPARATOR = " > ";
2
+ export const MAX_SECTION_DEPTH = 50;
3
+ /**
4
+ * Creates a memoized section lookup. Sections passed in `preloaded` (e.g. from a single
5
+ * `getSections` call) are served from memory; anything missing is fetched lazily via
6
+ * `client.getSection`. Failed lookups resolve to `null`.
7
+ */
8
+ export function createSectionLookup(client, preloaded = []) {
9
+ const cache = new Map();
10
+ for (const section of preloaded) {
11
+ cache.set(section.id, section);
12
+ }
13
+ return async (sectionId) => {
14
+ const cached = cache.get(sectionId);
15
+ if (cached) {
16
+ return cached;
17
+ }
18
+ const section = await client.getSection(sectionId).catch(() => null);
19
+ if (section) {
20
+ cache.set(sectionId, section);
21
+ }
22
+ return section ?? null;
23
+ };
24
+ }
25
+ /**
26
+ * Resolves the section hierarchy from root to leaf by walking `parent_id`.
27
+ *
28
+ * - Returns `[]` if the leaf section itself cannot be resolved (or has no name).
29
+ * - Falls back to `[leafName]` if any ancestor cannot be resolved, a cycle is detected,
30
+ * or the hierarchy exceeds `MAX_SECTION_DEPTH`.
31
+ */
32
+ export async function resolveSectionPath(sectionId, lookup) {
33
+ const leaf = await lookup(sectionId);
34
+ if (!leaf?.name) {
35
+ return [];
36
+ }
37
+ const names = [leaf.name];
38
+ const visited = new Set([sectionId]);
39
+ let parentId = leaf.parent_id;
40
+ while (parentId !== null && parentId !== undefined) {
41
+ if (visited.has(parentId) || names.length >= MAX_SECTION_DEPTH) {
42
+ return [leaf.name];
43
+ }
44
+ visited.add(parentId);
45
+ const parent = await lookup(parentId);
46
+ if (!parent?.name) {
47
+ return [leaf.name];
48
+ }
49
+ names.unshift(parent.name);
50
+ parentId = parent.parent_id;
51
+ }
52
+ return names;
53
+ }
54
+ /**
55
+ * Formats a section path for Markdown output. Literal `>` characters inside section names
56
+ * are escaped as `\>` so they cannot be confused with the path separator.
57
+ */
58
+ export function formatSectionPath(names) {
59
+ return names.map(name => name.replace(/>/g, "\\>")).join(SECTION_PATH_SEPARATOR);
60
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "3.2.0";
1
+ export const VERSION = "3.3.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uarlouski/testrail-mcp-server",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "mcpName": "io.github.uarlouski/testrail-mcp-server",
5
5
  "description": "Model Context Protocol (MCP) server for TestRail: let Claude, Cursor, and Windsurf manage test cases, runs, results, and attachments.",
6
6
  "main": "dist/index.js",
@@ -62,7 +62,7 @@
62
62
  "homepage": "https://uarlouski.github.io/testrail-mcp-server/",
63
63
  "license": "Apache-2.0",
64
64
  "dependencies": {
65
- "@modelcontextprotocol/sdk": "^1.30.0",
65
+ "@modelcontextprotocol/sdk": "^1.32.1",
66
66
  "archiver": "^7.0.1",
67
67
  "dotenv": "^17.4.2",
68
68
  "zod": "^4.6.5"