@zereight/mcp-gitlab 2.3.18-next.189 → 2.3.18-next.191

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/build/index.js CHANGED
@@ -118,6 +118,7 @@ import { redactUrlSecretsInError, redactUrlSecretsInErrorMessage, redactUrlSecre
118
118
  import { createMaskingPolicyResolver, getManagedMaskingProjectIds, } from "./masking/index.js";
119
119
  import { checkForNewVersion } from "./utils/version-check.js";
120
120
  import { assertGitLabVersionAtLeast } from "./utils/gitlab-version-gate.js";
121
+ import { createUnsupportedWidgetSelections, mergeUnsupportedWidgetSelections, parseUnsupportedWidgetSelections, pruneUnsupportedWidgetSelections, } from "./utils/work-item-widget-compat.js";
121
122
  import { fetchWithValidatedRedirects } from "./utils/safe-redirect-fetch.js";
122
123
  import { fetchStatusBeforeDeadline } from "./utils/poll-deadline.js";
123
124
  import { getUniqueApprovalUsers, inferMergeRequestApproved, MERGE_REQUEST_DEPLOYMENT_SUMMARY_LIMIT, parseApprovalsResponse, sortDeploymentsByCreatedAtDesc, toMergeRequestDeploymentSummaryRecord, } from "./utils/merge-request-summary.js";
@@ -1782,16 +1783,20 @@ async function deleteIssue(projectId, issueIid) {
1782
1783
  await handleGitLabError(response);
1783
1784
  }
1784
1785
  // --- GraphQL helper ---
1786
+ /** GraphQL endpoint for the effective API URL (GITLAB_GRAPHQL_URL wins). */
1787
+ function getGraphQLUrl() {
1788
+ const apiUrl = new URL(getEffectiveApiUrl());
1789
+ const restPath = apiUrl.pathname || "";
1790
+ const idx = restPath.lastIndexOf("/api/v4");
1791
+ const prefix = idx >= 0 ? restPath.slice(0, idx) : "";
1792
+ return process.env.GITLAB_GRAPHQL_URL || `${apiUrl.origin}${prefix}/api/graphql`;
1793
+ }
1785
1794
  /**
1786
1795
  * Execute a GraphQL query against the GitLab instance.
1787
1796
  * Reusable helper for work item operations.
1788
1797
  */
1789
1798
  async function executeGraphQL(query, variables = {}) {
1790
- const apiUrl = new URL(getEffectiveApiUrl());
1791
- const restPath = apiUrl.pathname || "";
1792
- const idx = restPath.lastIndexOf("/api/v4");
1793
- const prefix = idx >= 0 ? restPath.slice(0, idx) : "";
1794
- const graphqlUrl = process.env.GITLAB_GRAPHQL_URL || `${apiUrl.origin}${prefix}/api/graphql`;
1799
+ const graphqlUrl = getGraphQLUrl();
1795
1800
  const response = await fetch(graphqlUrl, {
1796
1801
  ...getFetchConfig(),
1797
1802
  method: "POST",
@@ -1811,6 +1816,49 @@ async function executeGraphQL(query, variables = {}) {
1811
1816
  }
1812
1817
  return json.data;
1813
1818
  }
1819
+ // Work item widget types/fields the instance lacks, keyed by GraphQL endpoint.
1820
+ // Filled only after a validation error, so Premium/Ultimate sends queries unchanged.
1821
+ const unsupportedWorkItemSelections = new Map();
1822
+ // GitLab reports at most five validation errors per response (validate_max_errors 5);
1823
+ // get_work_item selects about a dozen Premium-only widget types and fields, so CE
1824
+ // needs a few rounds before the document validates.
1825
+ const MAX_WORK_ITEM_QUERY_RETRIES = 5;
1826
+ /**
1827
+ * executeGraphQL for work item documents whose `... on WorkItemWidget*` fragments
1828
+ * exist only on Premium/Ultimate or newer GitLab (#959). When GitLab rejects the
1829
+ * document because a widget type or field does not exist there, drop that selection
1830
+ * and retry. The failure is static validation, so nothing ran yet and retrying a
1831
+ * mutation is safe. Removals are remembered per endpoint so later calls skip the
1832
+ * extra round trip.
1833
+ */
1834
+ async function executeWorkItemGraphQL(query, variables = {}) {
1835
+ const endpoint = getGraphQLUrl();
1836
+ const known = unsupportedWorkItemSelections.get(endpoint);
1837
+ let current = known ? pruneUnsupportedWidgetSelections(query, known) : query;
1838
+ for (let retries = 0;; retries++) {
1839
+ try {
1840
+ return await executeGraphQL(current, variables);
1841
+ }
1842
+ catch (error) {
1843
+ const found = error instanceof Error ? parseUnsupportedWidgetSelections(error.message) : null;
1844
+ if (!found || retries >= MAX_WORK_ITEM_QUERY_RETRIES)
1845
+ throw error;
1846
+ const pruned = pruneUnsupportedWidgetSelections(current, found);
1847
+ if (pruned === current)
1848
+ throw error;
1849
+ const remembered = unsupportedWorkItemSelections.get(endpoint);
1850
+ if (remembered) {
1851
+ mergeUnsupportedWidgetSelections(remembered, found);
1852
+ }
1853
+ else {
1854
+ const fresh = createUnsupportedWidgetSelections();
1855
+ mergeUnsupportedWidgetSelections(fresh, found);
1856
+ unsupportedWorkItemSelections.set(endpoint, fresh);
1857
+ }
1858
+ current = pruned;
1859
+ }
1860
+ }
1861
+ }
1814
1862
  /**
1815
1863
  * Resolve a namespace path and issue IID to a work item GraphQL GID.
1816
1864
  */
@@ -1954,7 +2002,7 @@ async function removeIssueParent(projectId, issueIid) {
1954
2002
  async function listIssueStatuses(projectId, workItemType = "issue") {
1955
2003
  const projectPath = await resolveProjectPath(projectId);
1956
2004
  const typeName = WORK_ITEM_TYPE_NAMES[workItemType] || "Issue";
1957
- const data = await executeGraphQL(`query($path: ID!, $typeName: IssueType) {
2005
+ const data = await executeWorkItemGraphQL(`query($path: ID!, $typeName: IssueType) {
1958
2006
  namespace(fullPath: $path) {
1959
2007
  workItemTypes(name: $typeName) {
1960
2008
  nodes {
@@ -2018,7 +2066,7 @@ async function listIssueStatuses(projectId, workItemType = "issue") {
2018
2066
  async function listCustomFieldDefinitions(projectId, workItemType = "issue") {
2019
2067
  const projectPath = await resolveProjectPath(projectId);
2020
2068
  const typeName = WORK_ITEM_TYPE_NAMES[workItemType] || "Issue";
2021
- const data = await executeGraphQL(`query($path: ID!, $typeName: IssueType) {
2069
+ const data = await executeWorkItemGraphQL(`query($path: ID!, $typeName: IssueType) {
2022
2070
  namespace(fullPath: $path) {
2023
2071
  workItemTypes(name: $typeName) {
2024
2072
  nodes {
@@ -2466,7 +2514,7 @@ async function resolveProjectOrGroupPath(projectId) {
2466
2514
  */
2467
2515
  async function getWorkItem(projectId, iid) {
2468
2516
  const projectPath = await resolveProjectPath(projectId);
2469
- const data = await executeGraphQL(`query($path: ID!, $iid: String!) {
2517
+ const data = await executeWorkItemGraphQL(`query($path: ID!, $iid: String!) {
2470
2518
  namespace(fullPath: $path) {
2471
2519
  workItem(iid: $iid) {
2472
2520
  id
@@ -2720,7 +2768,7 @@ async function listWorkItems(projectId, options) {
2720
2768
  if (options.after) {
2721
2769
  variables.after = options.after;
2722
2770
  }
2723
- const data = await executeGraphQL(`query($path: ID!, $types: [IssueType!], $state: IssuableState, $search: String, $assigneeUsernames: [String!], $labelName: [String!], $first: Int, $after: String) {
2771
+ const data = await executeWorkItemGraphQL(`query($path: ID!, $types: [IssueType!], $state: IssuableState, $search: String, $assigneeUsernames: [String!], $labelName: [String!], $first: Int, $after: String) {
2724
2772
  ${rootField}(fullPath: $path) {
2725
2773
  workItems(types: $types, state: $state, search: $search, assigneeUsernames: $assigneeUsernames, labelName: $labelName, first: $first, after: $after) {
2726
2774
  nodes {
@@ -3073,7 +3121,7 @@ async function updateWorkItem(projectId, iid, options) {
3073
3121
  errors
3074
3122
  }
3075
3123
  }`;
3076
- const data = await executeGraphQL(mutation, variables);
3124
+ const data = await executeWorkItemGraphQL(mutation, variables);
3077
3125
  if (data.workItemUpdate.errors?.length > 0) {
3078
3126
  throw new Error(`Failed to update work item: ${data.workItemUpdate.errors.join(", ")}`);
3079
3127
  }
@@ -630,6 +630,7 @@ class GitLabOAuthServerProvider {
630
630
  return false;
631
631
  }
632
632
  // ---- Refresh token -----------------------------------------------------
633
+ /** Refresh once, preserving successful tokens while sanitizing failures and releasing rejected bodies. */
633
634
  async exchangeRefreshToken(_client, refreshToken, scopes, resource) {
634
635
  if (this._disableRefreshToken) {
635
636
  // invalid_grant makes MCP clients drop stored tokens and restart the
@@ -645,14 +646,29 @@ class GitLabOAuthServerProvider {
645
646
  params.set("scope", scopes.join(" "));
646
647
  if (resource)
647
648
  params.set("resource", resource.href);
648
- const response = await fetch(`${this._gitlabBaseUrl}/oauth/token`, {
649
- method: "POST",
650
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
651
- body: params.toString(),
652
- });
649
+ let response;
650
+ try {
651
+ response = await fetch(`${this._gitlabBaseUrl}/oauth/token`, {
652
+ method: "POST",
653
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
654
+ body: params.toString(),
655
+ });
656
+ }
657
+ catch {
658
+ // Fetch errors may contain request URLs or credentials. Do not expose them.
659
+ logger.error("GitLab token refresh transport failed");
660
+ throw new ServerError("GitLab token refresh temporarily unavailable");
661
+ }
653
662
  if (!response.ok) {
654
- const body = await response.text();
655
- logger.error(`Token refresh failed (${response.status}): ${body}`);
663
+ let body;
664
+ try {
665
+ body = await response.text();
666
+ }
667
+ catch {
668
+ logger.error({ status: response.status }, "GitLab token refresh response unavailable");
669
+ throw new ServerError(`Token refresh failed: ${response.status}`);
670
+ }
671
+ logger.error({ status: response.status }, "GitLab token refresh rejected");
656
672
  throw tokenEndpointError("Token refresh", response.status, body);
657
673
  }
658
674
  const data = await response.json();
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Work item GraphQL queries select widget fragments that only exist on
3
+ * GitLab Premium/Ultimate (WorkItemWidgetStatus, WorkItemWidgetWeight, ...) or
4
+ * only on newer releases. GitLab validates the whole document, so on CE a
5
+ * single unknown fragment condition fails the request with
6
+ * "No such type WorkItemWidgetStatus, so it can't be a fragment condition" or
7
+ * "Field 'blocked' doesn't exist on type 'WorkItemWidgetLinkedItems'".
8
+ *
9
+ * This module reads those validation errors and removes the named selections
10
+ * from the query so the caller can retry. GitLab reports at most five
11
+ * validation errors per response (`validate_max_errors 5`), so one retry may
12
+ * surface more; callers loop until the query validates. See issue #959.
13
+ */
14
+ // Only work item types are handled; other validation errors surface unchanged.
15
+ const MISSING_TYPE_PATTERN = /No such type (WorkItem\w*)\b/g;
16
+ const MISSING_FIELD_PATTERN = /Field '(\w+)' doesn't exist on type '(WorkItem\w*)'/g;
17
+ export function createUnsupportedWidgetSelections() {
18
+ return { types: new Set(), fields: new Map() };
19
+ }
20
+ /**
21
+ * Extract unsupported work item types/fields from a GraphQL error message.
22
+ * Returns null when the message names none.
23
+ */
24
+ export function parseUnsupportedWidgetSelections(message) {
25
+ const found = createUnsupportedWidgetSelections();
26
+ for (const match of message.matchAll(MISSING_TYPE_PATTERN)) {
27
+ found.types.add(match[1]);
28
+ }
29
+ for (const match of message.matchAll(MISSING_FIELD_PATTERN)) {
30
+ const [, field, type] = match;
31
+ const fields = found.fields.get(type) ?? new Set();
32
+ fields.add(field);
33
+ found.fields.set(type, fields);
34
+ }
35
+ return found.types.size > 0 || found.fields.size > 0 ? found : null;
36
+ }
37
+ /** Add everything in `source` to `target`. */
38
+ export function mergeUnsupportedWidgetSelections(target, source) {
39
+ for (const type of source.types) {
40
+ target.types.add(type);
41
+ }
42
+ for (const [type, fields] of source.fields) {
43
+ const existing = target.fields.get(type) ?? new Set();
44
+ for (const field of fields) {
45
+ existing.add(field);
46
+ }
47
+ target.fields.set(type, existing);
48
+ }
49
+ }
50
+ /** Index just past the `}` that closes the `{` at `openIndex`. */
51
+ function skipBalanced(source, openIndex, open, close) {
52
+ let depth = 0;
53
+ for (let i = openIndex; i < source.length; i++) {
54
+ const ch = source[i];
55
+ if (ch === open)
56
+ depth++;
57
+ else if (ch === close && --depth === 0)
58
+ return i + 1;
59
+ }
60
+ return source.length;
61
+ }
62
+ function skipWhitespace(source, index) {
63
+ while (index < source.length && /[\s,]/.test(source[index]))
64
+ index++;
65
+ return index;
66
+ }
67
+ /**
68
+ * Remove the named top-level fields (with their arguments and sub-selections)
69
+ * from a fragment body. Nested selections and fragment spreads are left alone.
70
+ */
71
+ function removeTopLevelFields(body, fields) {
72
+ let result = "";
73
+ let i = 0;
74
+ while (i < body.length) {
75
+ const ch = body[i];
76
+ if (body.startsWith("...", i)) {
77
+ // Keep `... on Type { ... }` and `...Fragment` as they are.
78
+ const spread = /\.\.\.(?:\s*on\s+\w+)?/y;
79
+ spread.lastIndex = i;
80
+ const match = spread.exec(body);
81
+ const end = match ? spread.lastIndex : i + 3;
82
+ result += body.slice(i, end);
83
+ i = end;
84
+ continue;
85
+ }
86
+ if (ch === "{" || ch === "(") {
87
+ const end = skipBalanced(body, i, ch, ch === "{" ? "}" : ")");
88
+ result += body.slice(i, end);
89
+ i = end;
90
+ continue;
91
+ }
92
+ if (/[A-Za-z_]/.test(ch)) {
93
+ const name = /\w+/y;
94
+ name.lastIndex = i;
95
+ const token = name.exec(body)?.[0] ?? ch;
96
+ let end = i + token.length;
97
+ let fieldName = token;
98
+ // `alias: field` — judge by the field name, remove alias and field together.
99
+ const afterToken = skipWhitespace(body, end);
100
+ if (body[afterToken] === ":") {
101
+ const aliased = /\w+/y;
102
+ aliased.lastIndex = skipWhitespace(body, afterToken + 1);
103
+ const target = aliased.exec(body);
104
+ if (target) {
105
+ fieldName = target[0];
106
+ end = aliased.lastIndex;
107
+ }
108
+ }
109
+ if (!fields.has(fieldName)) {
110
+ result += body.slice(i, end);
111
+ i = end;
112
+ continue;
113
+ }
114
+ // Drop arguments and sub-selection that belong to the removed field.
115
+ let next = skipWhitespace(body, end);
116
+ if (body[next] === "(")
117
+ next = skipWhitespace(body, skipBalanced(body, next, "(", ")"));
118
+ if (body[next] === "{")
119
+ next = skipBalanced(body, next, "{", "}");
120
+ i = next;
121
+ continue;
122
+ }
123
+ result += ch;
124
+ i++;
125
+ }
126
+ return result;
127
+ }
128
+ /**
129
+ * Return `query` without the fragments whose condition type is unsupported and
130
+ * without the unsupported fields inside the remaining fragments. Returns the
131
+ * input unchanged (same string) when nothing applies.
132
+ */
133
+ export function pruneUnsupportedWidgetSelections(query, unsupported) {
134
+ if (unsupported.types.size === 0 && unsupported.fields.size === 0)
135
+ return query;
136
+ const fragmentPattern = /\.\.\.\s*on\s+(\w+)\s*\{/g;
137
+ const starts = Array.from(query.matchAll(fragmentPattern)).map(match => ({
138
+ index: match.index,
139
+ type: match[1],
140
+ openOffset: match[0].length - 1,
141
+ }));
142
+ // Walk from the last fragment backwards so earlier indexes stay valid while the
143
+ // text after them changes. Brace matching runs on the current text, so a nested
144
+ // fragment that was already rewritten is measured correctly.
145
+ let result = query;
146
+ for (let n = starts.length - 1; n >= 0; n--) {
147
+ const { index, type, openOffset } = starts[n];
148
+ const openIndex = index + openOffset;
149
+ const closeIndex = skipBalanced(result, openIndex, "{", "}");
150
+ if (unsupported.types.has(type)) {
151
+ result = result.slice(0, index) + result.slice(closeIndex);
152
+ continue;
153
+ }
154
+ const fields = unsupported.fields.get(type);
155
+ if (!fields || fields.size === 0)
156
+ continue;
157
+ const body = result.slice(openIndex + 1, closeIndex - 1);
158
+ const pruned = removeTopLevelFields(body, fields);
159
+ if (pruned === body)
160
+ continue;
161
+ // An empty selection set is invalid GraphQL, so drop the fragment instead.
162
+ result =
163
+ pruned.trim().length === 0
164
+ ? result.slice(0, index) + result.slice(closeIndex)
165
+ : result.slice(0, openIndex + 1) + pruned + result.slice(closeIndex - 1);
166
+ }
167
+ return result;
168
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zereight/mcp-gitlab",
3
- "version": "2.3.18-next.189",
3
+ "version": "2.3.18-next.191",
4
4
  "mcpName": "io.github.zereight/gitlab-mcp",
5
5
  "description": "GitLab MCP server for projects, merge requests, issues, pipelines, wiki, releases, and more",
6
6
  "keywords": [