simplify3x-connect 0.31.9 → 0.31.11

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.
Files changed (205) hide show
  1. package/README.md +18 -0
  2. package/assets/tessdata/eng.traineddata +0 -0
  3. package/dist/adapters/remoteMcp/adapter.d.ts +1 -1
  4. package/dist/adapters/remoteMcp/adapter.d.ts.map +1 -1
  5. package/dist/adapters/remoteMcp/adapter.js +6 -5
  6. package/dist/adapters/remoteMcp/adapter.js.map +1 -1
  7. package/dist/adapters/simplifyqa/adapter.d.ts +46 -2
  8. package/dist/adapters/simplifyqa/adapter.d.ts.map +1 -1
  9. package/dist/adapters/simplifyqa/adapter.js +434 -23
  10. package/dist/adapters/simplifyqa/adapter.js.map +1 -1
  11. package/dist/adapters/simplifyqa/appProfile.d.ts +25 -0
  12. package/dist/adapters/simplifyqa/appProfile.d.ts.map +1 -0
  13. package/dist/adapters/simplifyqa/appProfile.js +137 -0
  14. package/dist/adapters/simplifyqa/appProfile.js.map +1 -0
  15. package/dist/adapters/simplifyqa/executionFailures.d.ts +53 -11
  16. package/dist/adapters/simplifyqa/executionFailures.d.ts.map +1 -1
  17. package/dist/adapters/simplifyqa/executionFailures.js +289 -46
  18. package/dist/adapters/simplifyqa/executionFailures.js.map +1 -1
  19. package/dist/adapters/simplifyqa/executionSources.d.ts +64 -0
  20. package/dist/adapters/simplifyqa/executionSources.d.ts.map +1 -0
  21. package/dist/adapters/simplifyqa/executionSources.js +138 -0
  22. package/dist/adapters/simplifyqa/executionSources.js.map +1 -0
  23. package/dist/adapters/simplifyqa/failureAnalysis.d.ts +18 -1
  24. package/dist/adapters/simplifyqa/failureAnalysis.d.ts.map +1 -1
  25. package/dist/adapters/simplifyqa/failureAnalysis.js +182 -10
  26. package/dist/adapters/simplifyqa/failureAnalysis.js.map +1 -1
  27. package/dist/adapters/simplifyqa/failureAnalysisCard.d.ts.map +1 -1
  28. package/dist/adapters/simplifyqa/failureAnalysisCard.js +45 -19
  29. package/dist/adapters/simplifyqa/failureAnalysisCard.js.map +1 -1
  30. package/dist/adapters/simplifyqa/failureAnalysisRun.d.ts +8 -1
  31. package/dist/adapters/simplifyqa/failureAnalysisRun.d.ts.map +1 -1
  32. package/dist/adapters/simplifyqa/failureAnalysisRun.js +108 -4
  33. package/dist/adapters/simplifyqa/failureAnalysisRun.js.map +1 -1
  34. package/dist/adapters/simplifyqa/failureAnalysisTypes.d.ts +65 -1
  35. package/dist/adapters/simplifyqa/failureAnalysisTypes.d.ts.map +1 -1
  36. package/dist/adapters/simplifyqa/failureAnalysisTypes.js +12 -1
  37. package/dist/adapters/simplifyqa/failureAnalysisTypes.js.map +1 -1
  38. package/dist/adapters/simplifyqa/failureHistory.d.ts +64 -20
  39. package/dist/adapters/simplifyqa/failureHistory.d.ts.map +1 -1
  40. package/dist/adapters/simplifyqa/failureHistory.js +88 -30
  41. package/dist/adapters/simplifyqa/failureHistory.js.map +1 -1
  42. package/dist/adapters/simplifyqa/failurePatterns.d.ts +11 -0
  43. package/dist/adapters/simplifyqa/failurePatterns.d.ts.map +1 -1
  44. package/dist/adapters/simplifyqa/failurePatterns.js +4 -3
  45. package/dist/adapters/simplifyqa/failurePatterns.js.map +1 -1
  46. package/dist/adapters/simplifyqa/failureReport.d.ts.map +1 -1
  47. package/dist/adapters/simplifyqa/failureReport.js +8 -0
  48. package/dist/adapters/simplifyqa/failureReport.js.map +1 -1
  49. package/dist/adapters/simplifyqa/failureReportModel.d.ts +125 -1
  50. package/dist/adapters/simplifyqa/failureReportModel.d.ts.map +1 -1
  51. package/dist/adapters/simplifyqa/failureReportModel.js +324 -4
  52. package/dist/adapters/simplifyqa/failureReportModel.js.map +1 -1
  53. package/dist/adapters/simplifyqa/failureReview.d.ts +1 -1
  54. package/dist/adapters/simplifyqa/failureReview.d.ts.map +1 -1
  55. package/dist/adapters/simplifyqa/failureReview.js +44 -8
  56. package/dist/adapters/simplifyqa/failureReview.js.map +1 -1
  57. package/dist/adapters/simplifyqa/failureSuggest.d.ts +4 -2
  58. package/dist/adapters/simplifyqa/failureSuggest.d.ts.map +1 -1
  59. package/dist/adapters/simplifyqa/failureSuggest.js +44 -14
  60. package/dist/adapters/simplifyqa/failureSuggest.js.map +1 -1
  61. package/dist/adapters/simplifyqa/failureTypes.d.ts +19 -0
  62. package/dist/adapters/simplifyqa/failureTypes.d.ts.map +1 -1
  63. package/dist/adapters/simplifyqa/heal/apply.d.ts +3 -1
  64. package/dist/adapters/simplifyqa/heal/apply.d.ts.map +1 -1
  65. package/dist/adapters/simplifyqa/heal/apply.js +5 -1
  66. package/dist/adapters/simplifyqa/heal/apply.js.map +1 -1
  67. package/dist/adapters/simplifyqa/heal/diagnose.d.ts.map +1 -1
  68. package/dist/adapters/simplifyqa/heal/diagnose.js +14 -0
  69. package/dist/adapters/simplifyqa/heal/diagnose.js.map +1 -1
  70. package/dist/adapters/simplifyqa/heal/plan.d.ts +2 -0
  71. package/dist/adapters/simplifyqa/heal/plan.d.ts.map +1 -1
  72. package/dist/adapters/simplifyqa/heal/plan.js +43 -0
  73. package/dist/adapters/simplifyqa/heal/plan.js.map +1 -1
  74. package/dist/adapters/simplifyqa/networkErrors.d.ts +11 -0
  75. package/dist/adapters/simplifyqa/networkErrors.d.ts.map +1 -0
  76. package/dist/adapters/simplifyqa/networkErrors.js +108 -0
  77. package/dist/adapters/simplifyqa/networkErrors.js.map +1 -0
  78. package/dist/adapters/simplifyqa/outage.d.ts +41 -0
  79. package/dist/adapters/simplifyqa/outage.d.ts.map +1 -0
  80. package/dist/adapters/simplifyqa/outage.js +108 -0
  81. package/dist/adapters/simplifyqa/outage.js.map +1 -0
  82. package/dist/adapters/simplifyqa/patternSplit.d.ts +32 -0
  83. package/dist/adapters/simplifyqa/patternSplit.d.ts.map +1 -0
  84. package/dist/adapters/simplifyqa/patternSplit.js +79 -0
  85. package/dist/adapters/simplifyqa/patternSplit.js.map +1 -0
  86. package/dist/adapters/simplifyqa/screenText.d.ts +84 -0
  87. package/dist/adapters/simplifyqa/screenText.d.ts.map +1 -0
  88. package/dist/adapters/simplifyqa/screenText.js +497 -0
  89. package/dist/adapters/simplifyqa/screenText.js.map +1 -0
  90. package/dist/adapters/simplifyqa/searchRegistry.d.ts.map +1 -1
  91. package/dist/adapters/simplifyqa/searchRegistry.js +22 -0
  92. package/dist/adapters/simplifyqa/searchRegistry.js.map +1 -1
  93. package/dist/adapters/types.d.ts +4 -1
  94. package/dist/adapters/types.d.ts.map +1 -1
  95. package/dist/cli.js +7 -1
  96. package/dist/cli.js.map +1 -1
  97. package/dist/domain/heal.d.ts +10 -0
  98. package/dist/domain/heal.d.ts.map +1 -1
  99. package/dist/domain/heal.js.map +1 -1
  100. package/dist/domain/types.d.ts +56 -0
  101. package/dist/domain/types.d.ts.map +1 -1
  102. package/dist/export/html.d.ts +26 -0
  103. package/dist/export/html.d.ts.map +1 -0
  104. package/dist/export/html.js +842 -0
  105. package/dist/export/html.js.map +1 -0
  106. package/dist/export/labelCompare.d.ts +36 -0
  107. package/dist/export/labelCompare.d.ts.map +1 -0
  108. package/dist/export/labelCompare.js +96 -0
  109. package/dist/export/labelCompare.js.map +1 -0
  110. package/dist/export/layout.d.ts +19 -10
  111. package/dist/export/layout.d.ts.map +1 -1
  112. package/dist/export/layout.js +40 -9
  113. package/dist/export/layout.js.map +1 -1
  114. package/dist/export/pdf.d.ts +31 -1
  115. package/dist/export/pdf.d.ts.map +1 -1
  116. package/dist/export/pdf.js +170 -34
  117. package/dist/export/pdf.js.map +1 -1
  118. package/dist/export/xlsx.d.ts +1 -1
  119. package/dist/export/xlsx.js +2 -2
  120. package/dist/export/xlsx.js.map +1 -1
  121. package/dist/initAgents.d.ts.map +1 -1
  122. package/dist/initAgents.js +28 -8
  123. package/dist/initAgents.js.map +1 -1
  124. package/dist/integration/actions.d.ts +85 -0
  125. package/dist/integration/actions.d.ts.map +1 -0
  126. package/dist/integration/actions.js +391 -0
  127. package/dist/integration/actions.js.map +1 -0
  128. package/dist/integration/apply.d.ts +105 -0
  129. package/dist/integration/apply.d.ts.map +1 -0
  130. package/dist/integration/apply.js +345 -0
  131. package/dist/integration/apply.js.map +1 -0
  132. package/dist/integration/clients.d.ts +129 -0
  133. package/dist/integration/clients.d.ts.map +1 -0
  134. package/dist/integration/clients.js +332 -0
  135. package/dist/integration/clients.js.map +1 -0
  136. package/dist/integration/defaults.d.ts +14 -0
  137. package/dist/integration/defaults.d.ts.map +1 -0
  138. package/dist/integration/defaults.js +61 -0
  139. package/dist/integration/defaults.js.map +1 -0
  140. package/dist/integration/dummyData.d.ts +11 -0
  141. package/dist/integration/dummyData.d.ts.map +1 -0
  142. package/dist/integration/dummyData.js +112 -0
  143. package/dist/integration/dummyData.js.map +1 -0
  144. package/dist/integration/normalize.d.ts +71 -0
  145. package/dist/integration/normalize.d.ts.map +1 -0
  146. package/dist/integration/normalize.js +194 -0
  147. package/dist/integration/normalize.js.map +1 -0
  148. package/dist/integration/setupCommand.d.ts +17 -0
  149. package/dist/integration/setupCommand.d.ts.map +1 -0
  150. package/dist/integration/setupCommand.js +126 -0
  151. package/dist/integration/setupCommand.js.map +1 -0
  152. package/dist/integration/types.d.ts +84 -0
  153. package/dist/integration/types.d.ts.map +1 -0
  154. package/dist/integration/types.js +2 -0
  155. package/dist/integration/types.js.map +1 -0
  156. package/dist/server.d.ts.map +1 -1
  157. package/dist/server.js +15 -2
  158. package/dist/server.js.map +1 -1
  159. package/dist/tools/desktopRecordingMode.d.ts +27 -0
  160. package/dist/tools/desktopRecordingMode.d.ts.map +1 -0
  161. package/dist/tools/desktopRecordingMode.js +40 -0
  162. package/dist/tools/desktopRecordingMode.js.map +1 -0
  163. package/dist/tools/discovery.tools.d.ts.map +1 -1
  164. package/dist/tools/discovery.tools.js +159 -16
  165. package/dist/tools/discovery.tools.js.map +1 -1
  166. package/dist/tools/executionPlan.tools.d.ts.map +1 -1
  167. package/dist/tools/executionPlan.tools.js +9 -6
  168. package/dist/tools/executionPlan.tools.js.map +1 -1
  169. package/dist/tools/failure.tools.d.ts +10 -0
  170. package/dist/tools/failure.tools.d.ts.map +1 -1
  171. package/dist/tools/failure.tools.js +140 -18
  172. package/dist/tools/failure.tools.js.map +1 -1
  173. package/dist/tools/failureExport.tools.d.ts +1 -1
  174. package/dist/tools/failureExport.tools.d.ts.map +1 -1
  175. package/dist/tools/failureExport.tools.js +69 -26
  176. package/dist/tools/failureExport.tools.js.map +1 -1
  177. package/dist/tools/heal.tools.js +1 -1
  178. package/dist/tools/heal.tools.js.map +1 -1
  179. package/dist/tools/integration.tools.d.ts +16 -0
  180. package/dist/tools/integration.tools.d.ts.map +1 -0
  181. package/dist/tools/integration.tools.js +704 -0
  182. package/dist/tools/integration.tools.js.map +1 -0
  183. package/dist/tools/recording.tools.d.ts.map +1 -1
  184. package/dist/tools/recording.tools.js +12 -4
  185. package/dist/tools/recording.tools.js.map +1 -1
  186. package/dist/tools/recordingNames.d.ts +16 -0
  187. package/dist/tools/recordingNames.d.ts.map +1 -1
  188. package/dist/tools/recordingNames.js +31 -0
  189. package/dist/tools/recordingNames.js.map +1 -1
  190. package/dist/tools/storySync.tools.d.ts.map +1 -1
  191. package/dist/tools/storySync.tools.js +2 -1
  192. package/dist/tools/storySync.tools.js.map +1 -1
  193. package/dist/tools/testcase.tools.d.ts +13 -1
  194. package/dist/tools/testcase.tools.d.ts.map +1 -1
  195. package/dist/tools/testcase.tools.js +80 -13
  196. package/dist/tools/testcase.tools.js.map +1 -1
  197. package/dist/tools/verdictMemory.d.ts +55 -0
  198. package/dist/tools/verdictMemory.d.ts.map +1 -0
  199. package/dist/tools/verdictMemory.js +117 -0
  200. package/dist/tools/verdictMemory.js.map +1 -0
  201. package/dist/version.d.ts +1 -1
  202. package/dist/version.d.ts.map +1 -1
  203. package/dist/version.js +1 -1
  204. package/dist/version.js.map +1 -1
  205. package/package.json +6 -2
@@ -0,0 +1,704 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { z } from 'zod';
3
+ import { ok, err } from '../mcpResult.js';
4
+ import { ExternalClient, ExternalError, SqaIntegrationClient } from '../integration/clients.js';
5
+ import { AZURE_HOOK_EVENTS, WEBHOOK_EVENTS, azureHookInstructions, azureHookUrl, azureTarget, digestOf, jiraTarget, planPrepare, runTwoWayTest, webhookInstructions, webhookUrl } from '../integration/actions.js';
6
+ import { FILE_ENV, credentialsPath, openSetupTerminal, setupCommand } from '../integration/setupCommand.js';
7
+ import { planApply, describeExisting, TOOLS, sameProject, existingProjectName } from '../integration/apply.js';
8
+ import { resolveDefault } from '../integration/defaults.js';
9
+ export const INTEGRATION_PRIVILEGE = 'allow_project_integration';
10
+ const CONFIRM_TTL_MS = 10 * 60 * 1000;
11
+ const AUTO_TOKEN = '__MCP_CREATES_SQA_TOKEN__';
12
+ const API_TOKEN_DAYS = 365;
13
+ const NOT_CONNECTED = 'Not connected to SimplifyQA. Use qa_connect first, then qa_switch_project to pick the project to integrate.';
14
+ const ONLY_SQA = 'Integration setup is available on SimplifyQA connections only.';
15
+ const toolArg = z.enum(['jira', 'azure']).describe('"jira" or "azure" (Azure DevOps)');
16
+ function loadExternalCredentials(tool, env) {
17
+ const prefix = tool === 'azure' ? 'QA_MCP_AZURE_' : 'QA_MCP_JIRA_';
18
+ let file = {};
19
+ const path = credentialsPath(tool, env);
20
+ try {
21
+ file = JSON.parse(readFileSync(path, 'utf8'));
22
+ }
23
+ catch {
24
+ file = {};
25
+ }
26
+ const baseUrl = env[`${prefix}BASE_URL`] ?? file.baseUrl;
27
+ const email = env[`${prefix}EMAIL`] ?? file.email;
28
+ const token = env[`${prefix}TOKEN`] ?? (tool === 'azure' ? file.pat : file.apiToken);
29
+ const extra = {};
30
+ const sqaApiToken = env[`${prefix}SQA_API_TOKEN`] ?? file.sqaApiToken;
31
+ const qaDefaultEmail = env[`${prefix}QA_DEFAULT_EMAIL`] ?? file.qaDefaultEmail;
32
+ if (sqaApiToken)
33
+ extra.sqaApiToken = sqaApiToken;
34
+ if (qaDefaultEmail)
35
+ extra.qaDefaultEmail = qaDefaultEmail;
36
+ const source = env[`${prefix}TOKEN`] ? `${prefix}* environment variables` : path ? `credentials file ${path}` : 'none';
37
+ return { creds: baseUrl && email && token ? { baseUrl, email, token } : null, extra, source };
38
+ }
39
+ const table = (head, rows) => [`| ${head.join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map((c) => String(c ?? '').replace(/\|/g, '\\|')).join(' | ')} |`)].join('\n');
40
+ const valuesText = (v) => (v?.length ? `${v.slice(0, 12).join(' / ')}${v.length > 12 ? ` / … (${v.length})` : ''}` : '');
41
+ function describeDiscovery(tool, ext, qa, existing) {
42
+ const T = TOOLS[tool];
43
+ const out = [`## ${T.name} ${ext.project}`];
44
+ for (const [name, t] of Object.entries(ext.types)) {
45
+ out.push('', `### ${T.typeWord}: ${name}${ext.entityExclude.includes(name) ? ' (sub-task; usually not mapped)' : ''}`, `Statuses: ${t.statuses.map((s) => `${s.name}${s.category ? ` [${s.category}]` : ''}`).join(', ') || '—'}`, table(['Field', 'Key', 'Type', 'Sync type', 'Required', 'Allowed values'], t.fields.map((f) => [f.name, f.key, f.type, f.syncType ?? 'not supported', f.required ? 'yes' : '', valuesText(f.values)])));
46
+ }
47
+ out.push('', '## SimplifyQA modules');
48
+ for (const m of qa) {
49
+ out.push('', `### ${m.name} (\`${m.key}\`)`, `Statuses: ${m.statuses.join(', ') || '—'}`, table(['Field', 'Key', 'Type', 'Required', 'Custom', 'Values'], m.fields.map((f) => [f.label, f.key, f.type, f.required ? 'yes' : '', f.custom ? 'yes' : '', valuesText(f.values)])));
50
+ }
51
+ const current = describeExisting(tool, existing);
52
+ out.push('', '## Current configuration');
53
+ if (!existing)
54
+ out.push('None for this project.');
55
+ else {
56
+ out.push(`${T.name} project ${existingProjectName(tool, existing)}.`);
57
+ for (const c of current)
58
+ out.push('', `**${c.module} → ${c.type}**`, table(['SimplifyQA field', `${T.name} field`, 'Default'], c.fields.map((f) => [f.sqaField, f.extField ?? '—', f.default === undefined ? '' : JSON.stringify(f.default)])));
59
+ }
60
+ return out.join('\n');
61
+ }
62
+ export function registerIntegrationTools(server, deps) {
63
+ const env = deps.env ?? process.env;
64
+ const state = { trace: [], discovery: null, existing: null, other: null, pending: null };
65
+ const guard = (fn) => async (a) => {
66
+ try {
67
+ if (!deps.isSimplifyqa())
68
+ return err(ONLY_SQA);
69
+ return await fn(a);
70
+ }
71
+ catch (e) {
72
+ return err(e instanceof Error ? e.message : String(e));
73
+ }
74
+ };
75
+ async function session() {
76
+ const adapter = deps.getAdapter();
77
+ const getCtx = adapter?.getSessionContext;
78
+ if (!adapter || !getCtx)
79
+ throw new Error(NOT_CONNECTED);
80
+ return { adapter, ctx: await getCtx.call(adapter) };
81
+ }
82
+ async function context() {
83
+ const { adapter, ctx } = await session();
84
+ if (!ctx.projectId)
85
+ throw new Error('No project selected. Pick the SimplifyQA project to integrate with qa_switch_project first.');
86
+ return { adapter, ctx, projectId: Number.parseInt(ctx.projectId, 10) };
87
+ }
88
+ const sqaClient = (ctx) => new SqaIntegrationClient(ctx, state.trace, deps.fetchImpl);
89
+ async function requirePrivilege(adapter, projectId, privilege = INTEGRATION_PRIVILEGE) {
90
+ if (!adapter.getProjectPrivileges)
91
+ return;
92
+ const p = await adapter.getProjectPrivileges(String(projectId));
93
+ if (!p.privileges.includes(privilege)) {
94
+ throw new Error(`You can't ${privilege === INTEGRATION_PRIVILEGE ? 'set up' : 'delete'} integrations in project ${projectId}: this needs the \`${privilege}\` privilege${p.roleName ? ` (your role "${p.roleName}" does not have it)` : ''}. Ask a project administrator to add it to your role.`);
95
+ }
96
+ }
97
+ const external = (tool) => {
98
+ const { creds } = loadExternalCredentials(tool, env);
99
+ if (!creds) {
100
+ const prefix = tool === 'azure' ? 'QA_MCP_AZURE_' : 'QA_MCP_JIRA_';
101
+ throw new Error(`${TOOLS[tool].name} credentials are not configured. Call integration_config with action "setup" and tool "${tool}": it opens a terminal window on the user's computer where they type the tokens hidden. Or the user runs ${setupCommand(tool)} in their own terminal (it asks for the ${TOOLS[tool].name} site, email and token, the token hidden, checks them and saves ${credentialsPath(tool, env)}); no reconnect is needed afterwards. ${FILE_ENV[tool]} or ${prefix}BASE_URL / ${prefix}EMAIL / ${prefix}TOKEN also work. Tokens are never accepted through chat.`);
102
+ }
103
+ return new ExternalClient(tool, creds, state.trace, deps.fetchImpl);
104
+ };
105
+ const needDiscovery = () => {
106
+ if (!state.discovery)
107
+ throw new Error('Run integration_lookup with what "fields" first.');
108
+ return state.discovery;
109
+ };
110
+ async function status() {
111
+ const lines = ['jira', 'azure'].map((t) => {
112
+ const { creds, source } = loadExternalCredentials(t, env);
113
+ return `- ${TOOLS[t].name}: ${creds ? `${creds.baseUrl} as ${creds.email} (${source})` : `not configured — integration_config action "setup" opens a terminal window for the user to enter the tokens`}`;
114
+ });
115
+ let project;
116
+ try {
117
+ project = String((await context()).projectId);
118
+ }
119
+ catch (e) {
120
+ project = e instanceof Error ? e.message : String(e);
121
+ }
122
+ const d = state.discovery;
123
+ lines.push(`- SimplifyQA project: ${project}`, `- Discovery: ${d ? `${TOOLS[d.tool].name} ${d.externalProject} ↔ SimplifyQA project ${d.projectId}${d.subProjectName ? ` · sub project ${d.subProjectName}` : ''}` : 'none'}`, `- Existing configuration: ${d ? (state.existing ? `${TOOLS[d.tool].name} ${existingProjectName(d.tool, state.existing)} (${Object.keys(state.existing.issueMap ?? {}).join(', ')})` : state.other ? `none; project already has a ${state.other} integration` : 'none') : 'unknown until discovery'}`, `- Pending save: ${state.pending ? `confirm token ${state.pending.token}` : 'none'}`, '', 'Flow: integration_lookup projects → integration_lookup fields → you propose the mapping from the discovered metadata and agree it with the user → integration_config apply (preview) → user approves → integration_config apply with the same mappings and the confirmToken.');
124
+ return ok(lines.join('\n'));
125
+ }
126
+ async function apply(a) {
127
+ const d = needDiscovery();
128
+ const { adapter, ctx, projectId } = await context();
129
+ if (projectId !== d.projectId)
130
+ throw new Error(`The active project changed to ${projectId} since discovery (${d.projectId}). Run integration_lookup with what "fields" again.`);
131
+ await requirePrivilege(adapter, projectId);
132
+ const sqa = sqaClient(ctx);
133
+ const existing = await sqa.findConfig(d.tool, projectId, d.subProjectId);
134
+ const otherTool = d.tool === 'azure' ? 'jira' : 'azure';
135
+ const other = existing ? null : await sqa.findConfig(otherTool, projectId);
136
+ const { creds, extra } = loadExternalCredentials(d.tool, env);
137
+ const tokenCustomer = (token) => new SqaIntegrationClient({ baseUrl: ctx.baseUrl, token }, state.trace, deps.fetchImpl).tokenCustomerId();
138
+ const tokenCustomers = {
139
+ session: await sqa.tokenCustomerId(),
140
+ credentials: extra.sqaApiToken ? await tokenCustomer(extra.sqaApiToken) : null,
141
+ stored: existing?.sqaToken?.includes('*') ? 'hidden' : existing?.sqaToken ? await tokenCustomer(existing.sqaToken) : null,
142
+ };
143
+ const autoToken = tokenCustomers.session !== null && (!extra.sqaApiToken || tokenCustomers.credentials !== tokenCustomers.session);
144
+ const planCredentials = creds ? { ...creds, ...extra, ...(autoToken ? { sqaApiToken: AUTO_TOKEN } : {}) } : null;
145
+ const planTokenCustomers = autoToken ? { ...tokenCustomers, credentials: tokenCustomers.session } : tokenCustomers;
146
+ const defaultErrors = [];
147
+ const mappings = [];
148
+ for (const m of a.mappings) {
149
+ const mod = d.qa.find((x) => x.key.toLowerCase() === m.module.toLowerCase() || x.name.toLowerCase() === m.module.toLowerCase());
150
+ const rawMod = mod ? d.raw[mod.key] : undefined;
151
+ const fields = [];
152
+ for (const f of m.fields ?? []) {
153
+ const rawField = rawMod?.fields.find((x) => x.key.toLowerCase() === f.sqaField.toLowerCase() || x.label.toLowerCase() === f.sqaField.toLowerCase());
154
+ if (f.default === undefined || !rawField) {
155
+ fields.push(f);
156
+ continue;
157
+ }
158
+ const r = await resolveDefault(rawField, f.default, (collection, value) => sqa.searchByName(collection, value, projectId));
159
+ if ('error' in r) {
160
+ defaultErrors.push(`${mod?.name ?? m.module}: ${r.error}`);
161
+ fields.push({ sqaField: f.sqaField, extField: f.extField });
162
+ }
163
+ else
164
+ fields.push({ ...f, default: r.value });
165
+ }
166
+ mappings.push({ ...m, fields });
167
+ }
168
+ const plan = planApply({
169
+ tool: d.tool, ext: d.ext, qa: d.qa, raw: d.raw, existing, mappings, projectId,
170
+ approver: ctx.userId ? `user ${ctx.userId}` : 'SimplifyQA session user',
171
+ ...(a.acknowledge ? { acknowledge: a.acknowledge } : {}),
172
+ credentials: planCredentials,
173
+ otherIntegration: other ? TOOLS[otherTool].name : null,
174
+ tokenCustomers: planTokenCustomers,
175
+ });
176
+ plan.blockers.unshift(...defaultErrors);
177
+ if (d.subProjectId !== null && plan.mode === 'create')
178
+ plan.body['subProjectId'] = d.subProjectId;
179
+ const name = TOOLS[d.tool].name;
180
+ const scope = d.subProjectName ? ` · sub project ${d.subProjectName}` : '';
181
+ const tokenLabel = `${name} integration · project ${projectId} (MCP)`;
182
+ const createsToken = JSON.stringify(plan.body).includes(AUTO_TOKEN);
183
+ plan.warnings = plan.warnings.map((w) => w.split(AUTO_TOKEN).join('a new SimplifyQA API token'));
184
+ if (createsToken)
185
+ plan.warnings.push(`A SimplifyQA API token "${tokenLabel}" will be created for your user (customer ${tokenCustomers.session}, valid ${API_TOKEN_DAYS} days) so the background sync can write into SimplifyQA. It is listed with your API tokens in SimplifyQA, where you can revoke it.`);
186
+ const summary = [
187
+ `**${plan.mode === 'update' ? `Update configuration ${existing?.id}` : 'Create a new configuration'}** · SimplifyQA project ${projectId}${scope} ↔ ${name} ${d.externalProject}`,
188
+ '', table(['Module', 'Type', 'Status', 'Added', 'Changed', 'Removed', 'Kept'], plan.modules.map((m) => [m.module, m.type, m.status, m.added, m.changed, m.removed, m.kept])),
189
+ ...plan.modules.filter((m) => m.fields?.some((f) => f.change !== 'kept')).map((m) => `\n**${m.module} → ${m.type}**\n${table(['SimplifyQA field', `${name} field`, 'Change'], (m.fields ?? []).filter((f) => f.change !== 'kept').map((f) => [f.qa, f.ext ?? '—', f.change]))}`),
190
+ plan.mode === 'update' ? `\nConnection details, counts and sync settings are not changed.${plan.replacesToken ? ' The stored SimplifyQA token is replaced (see warnings).' : ' Tokens are not changed.'}` : `\nNew record from the ${name} credentials; data flow on in both directions for every module.`,
191
+ plan.warnings.length ? `\n**Warnings**\n${plan.warnings.map((w) => `- ${w}`).join('\n')}` : '',
192
+ ].join('\n');
193
+ if (plan.blockers.length) {
194
+ state.pending = null;
195
+ return ok(`${summary}\n\n**Cannot save — fix these in the mapping and call again:**\n${plan.blockers.map((b) => `- ${b}`).join('\n')}`, { saved: false, blockers: plan.blockers, warnings: plan.warnings });
196
+ }
197
+ if (!a.confirmToken) {
198
+ state.pending = { token: `c_${plan.digest.slice(0, 8)}`, digest: plan.digest, expires: Date.now() + CONFIRM_TTL_MS };
199
+ return ok(`${summary}\n\n**Nothing has been saved.** Show this to the user. If they approve, call integration_config action "apply" again with the same mappings and confirmToken "${state.pending.token}" (valid 10 minutes).`, { saved: false, confirmToken: state.pending.token, warnings: plan.warnings });
200
+ }
201
+ const p = state.pending;
202
+ if (!p || a.confirmToken !== p.token)
203
+ throw new Error('Unknown confirm token. Call integration_config action "apply" without a token to get a fresh preview.');
204
+ if (Date.now() > p.expires) {
205
+ state.pending = null;
206
+ throw new Error('The confirm token expired. Call integration_config action "apply" without a token for a fresh preview.');
207
+ }
208
+ if (plan.digest !== p.digest) {
209
+ state.pending = null;
210
+ throw new Error('The mapping or the saved configuration changed since the preview. Call integration_config action "apply" without a token and show the new preview.');
211
+ }
212
+ state.pending = null;
213
+ if (createsToken) {
214
+ const token = await sqa.createApiToken(tokenLabel, new Date(Date.now() + API_TOKEN_DAYS * 86400000).toISOString());
215
+ const swap = (o) => {
216
+ for (const [k, v] of Object.entries(o)) {
217
+ if (v === AUTO_TOKEN)
218
+ o[k] = token;
219
+ else if (v && typeof v === 'object' && !Array.isArray(v))
220
+ swap(v);
221
+ }
222
+ };
223
+ swap(plan.body);
224
+ }
225
+ await sqa.saveConfig(d.tool, plan.body);
226
+ const after = await sqa.findConfig(d.tool, projectId, d.subProjectId);
227
+ state.existing = after;
228
+ if (after && d.tool === 'jira' && d.subProjectId !== null) {
229
+ await sqa.linkJiraSubProject(projectId, { subProjectId: d.subProjectId, jiraProjectKey: d.ext.projectKey || d.externalProject, jiraProjectName: String(d.ext.projectRaw['name'] ?? d.ext.project) });
230
+ }
231
+ const counts = after ? Object.entries(after.issueMap ?? {}).map(([t, m]) => `${t} → ${m} (${(after.fieldsMap?.[`${m}__${t}`] ?? []).length} fields)`).join(', ') : 'not found';
232
+ return ok(`**Saved.** Configuration ${after?.id ?? ''} ${plan.mode === 'update' ? 'updated' : 'created'}.\nRead back: ${counts}.\nOpen Marketplace → ${name} in project ${projectId} (hard refresh) to see it. Sync has not been started.`, { saved: true, id: after?.id ?? null });
233
+ }
234
+ let pendingDelete = null;
235
+ async function remove(a) {
236
+ const { adapter, ctx, projectId } = await context();
237
+ await requirePrivilege(adapter, projectId, 'delete_project_integration');
238
+ const sqa = sqaClient(ctx);
239
+ const sub = state.discovery?.tool === a.tool && state.discovery.projectId === projectId ? state.discovery : null;
240
+ const subProjectId = sub?.subProjectId ?? null;
241
+ const config = await sqa.findConfig(a.tool, projectId, subProjectId);
242
+ const name = TOOLS[a.tool].name;
243
+ const scope = sub?.subProjectName ? ` · sub project ${sub.subProjectName}` : '';
244
+ if (!config) {
245
+ pendingDelete = null;
246
+ return ok(`Project ${projectId}${scope} has no ${name} configuration; nothing to delete.`, { deleted: false });
247
+ }
248
+ const what = `${name} configuration ${config.id} · SimplifyQA project ${projectId}${scope} ↔ ${existingProjectName(a.tool, config)} · mapped: ${Object.entries(config.issueMap ?? {}).map(([t, m]) => `${t} → ${m}`).join(', ') || 'nothing'}`;
249
+ if (!a.confirmToken) {
250
+ pendingDelete = { token: `d_${Math.random().toString(36).slice(2, 10)}`, tool: a.tool, configId: config.id, expires: Date.now() + CONFIRM_TTL_MS };
251
+ return ok(`**Will delete:** ${what}.\nSync stops; records already synced stay in SimplifyQA and ${name}.\n**Nothing has been deleted.** If the user agrees, call integration_config action "delete" again with confirmToken "${pendingDelete.token}" (valid 10 minutes).`, { deleted: false, confirmToken: pendingDelete.token });
252
+ }
253
+ const p = pendingDelete;
254
+ if (!p || p.token !== a.confirmToken || p.tool !== a.tool || p.configId !== config.id)
255
+ throw new Error('Unknown confirm token. Call integration_config action "delete" without a token for a fresh preview.');
256
+ if (Date.now() > p.expires) {
257
+ pendingDelete = null;
258
+ throw new Error('The confirm token expired. Call integration_config action "delete" without a token for a fresh preview.');
259
+ }
260
+ pendingDelete = null;
261
+ await sqa.deleteConfig(a.tool, config.id);
262
+ const after = await sqa.findConfig(a.tool, projectId, subProjectId);
263
+ if (state.discovery?.tool === a.tool && state.discovery.projectId === projectId)
264
+ state.existing = after;
265
+ return ok(after ? `The delete request was accepted but configuration ${after.id} is still active; check Marketplace → ${name}.` : `**Deleted** ${what}. Hard-refresh Marketplace → ${name} to see it gone.`, { deleted: !after });
266
+ }
267
+ const mappingSchema = z.array(z.object({
268
+ module: z.string().describe('SimplifyQA module key or name'),
269
+ type: z.string().nullable().describe('Jira issue type / Azure DevOps work item type name; null removes this module from the integration'),
270
+ fields: z.array(z.object({
271
+ sqaField: z.string().describe('SimplifyQA field key or label'),
272
+ extField: z.string().optional().describe('Jira / Azure DevOps field key or name; omit for a default-only field'),
273
+ default: z.union([z.string(), z.number(), z.array(z.union([z.string(), z.number()]))]).optional()
274
+ .describe('Value SimplifyQA uses when the external value is missing (needed for mandatory fields with no external counterpart). Lists: option key or label; release / sprint / user / linked record: name or id; dates: YYYY-MM-DD'),
275
+ })).optional()
276
+ .describe('The COMPLETE field list for this module: pairs left out are removed from the saved mapping'),
277
+ })).describe('action "apply": only the modules to change; modules not listed keep their current mapping');
278
+ let pendingPrepare = null;
279
+ async function prepare(input, confirmToken) {
280
+ const d = needDiscovery();
281
+ const { adapter, ctx, projectId } = await context();
282
+ if (projectId !== d.projectId)
283
+ throw new Error(`The active project changed to ${projectId} since discovery (${d.projectId}). Run integration_lookup with what "fields" again.`);
284
+ await requirePrivilege(adapter, projectId);
285
+ const sqa = sqaClient(ctx);
286
+ const customerId = await sqa.tokenCustomerId();
287
+ if (customerId === null)
288
+ throw new Error('Could not read the SimplifyQA customer of this session. Reconnect and try again.');
289
+ const userId = ctx.userId ? Number(ctx.userId) : null;
290
+ const items = await planPrepare({ input, qa: d.qa, raw: d.raw, sqa, projectId, customerId, userId, ext: d.ext, toolName: TOOLS[d.tool].name });
291
+ const digest = digestOf({ projectId, items: items.map(({ what, status, note }) => ({ what, status, note })) });
292
+ const summary = table(['Item', 'Status', 'Note'], items.map((i) => [i.what, i.status === 'create' ? 'will be created' : i.status === 'exists' ? 'exists' : 'cannot create', i.note ?? '']));
293
+ const toCreate = items.filter((i) => i.status === 'create');
294
+ if (!toCreate.length) {
295
+ pendingPrepare = null;
296
+ return ok(`${summary}
297
+
298
+ Nothing to create.`, { created: 0 });
299
+ }
300
+ if (!confirmToken) {
301
+ pendingPrepare = { token: `p_${digest.slice(0, 8)}`, digest, expires: Date.now() + CONFIRM_TTL_MS };
302
+ return ok(`**Create in SimplifyQA project ${projectId}:**\n\n${summary}\n\n**Nothing has been created.** Show this to the user. If they agree, call integration_config action "prepare" again with the same prepare object and confirmToken "${pendingPrepare.token}" (valid 10 minutes).`, { created: 0, confirmToken: pendingPrepare.token });
303
+ }
304
+ const p = pendingPrepare;
305
+ if (!p || p.token !== confirmToken)
306
+ throw new Error('Unknown confirm token. Call integration_config action "prepare" without a token for a fresh preview.');
307
+ if (Date.now() > p.expires) {
308
+ pendingPrepare = null;
309
+ throw new Error('The confirm token expired. Call integration_config action "prepare" without a token for a fresh preview.');
310
+ }
311
+ if (p.digest !== digest) {
312
+ pendingPrepare = null;
313
+ throw new Error('The request or SimplifyQA changed since the preview. Call integration_config action "prepare" without a token and show the new preview.');
314
+ }
315
+ pendingPrepare = null;
316
+ const done = [];
317
+ for (const item of toCreate) {
318
+ try {
319
+ await item.run();
320
+ done.push(`- created: ${item.what}`);
321
+ }
322
+ catch (e) {
323
+ done.push(`- **failed**: ${item.what}: ${e instanceof Error ? e.message : String(e)}`, '- stopped; nothing after this was created');
324
+ break;
325
+ }
326
+ }
327
+ const { qa, raw } = await sqa.discover(projectId);
328
+ state.discovery = { ...d, qa, raw };
329
+ return ok(`${done.join('\n')}\n\nSimplifyQA fields were read again, so the new fields and values can be used in integration_config action "apply" now.`, { created: done.filter((l) => l.startsWith('- created')).length });
330
+ }
331
+ let pendingWebhook = null;
332
+ let pendingAzureHook = null;
333
+ async function azureHook(confirmToken, d, ctx, sqa, projectId, customerId) {
334
+ const url = azureHookUrl(ctx.baseUrl);
335
+ const azure = external('azure');
336
+ const projectGuid = d.ext.projectId || (await azure.projectGuid(d.externalProject));
337
+ let hooks;
338
+ try {
339
+ hooks = await azure.serviceHooks();
340
+ }
341
+ catch (e) {
342
+ if (e instanceof ExternalError && (e.status === 401 || e.status === 403)) {
343
+ return ok(`The Azure DevOps token cannot read service hooks: that needs a project administrator (Edit subscriptions) and a PAT with the Service Hooks scope.\n\n${azureHookInstructions(url, d.externalProject)}`, { registered: false, url });
344
+ }
345
+ throw e;
346
+ }
347
+ const mine = hooks.filter((h) => h.consumerInputs?.['url'] === url && h.publisherInputs?.['projectId'] === projectGuid);
348
+ const missing = AZURE_HOOK_EVENTS.filter((ev) => !mine.some((h) => h.eventType === ev));
349
+ const disabled = mine.filter((h) => h.status && h.status !== 'enabled').map((h) => h.eventType);
350
+ if (!missing.length)
351
+ return ok(`Azure DevOps service hooks are already registered for ${d.externalProject} → ${url} (${AZURE_HOOK_EVENTS.join(', ')})${disabled.length ? `, but **not enabled**: ${disabled.join(', ')}; enable them in Project settings → Service hooks` : ''}.`, { registered: true, enabled: !disabled.length, url });
352
+ const label = `Azure webhook · project ${projectId} (MCP)`;
353
+ if (!confirmToken) {
354
+ pendingAzureHook = { token: `w_${digestOf([url, projectGuid, missing]).slice(0, 8)}`, url, projectGuid, missing, expires: Date.now() + CONFIRM_TTL_MS };
355
+ return ok(`**Register Azure DevOps service hooks** so work item changes in ${d.externalProject} reach SimplifyQA right away:\n- URL: ${url}\n- Events: ${missing.join(', ')}\n- Authorization: a new SimplifyQA API token "${label}" for your user (customer ${customerId}, valid ${API_TOKEN_DAYS} days), created when you confirm\n\n**Nothing has been registered.** If the user agrees, call integration_config action "webhook" again with confirmToken "${pendingAzureHook.token}" (valid 10 minutes).`, { registered: false, url, confirmToken: pendingAzureHook.token });
356
+ }
357
+ const p = pendingAzureHook;
358
+ if (!p || p.token !== confirmToken || p.url !== url || p.projectGuid !== projectGuid)
359
+ throw new Error('Unknown confirm token. Call integration_config action "webhook" without a token for a fresh preview.');
360
+ if (Date.now() > p.expires) {
361
+ pendingAzureHook = null;
362
+ throw new Error('The confirm token expired. Call integration_config action "webhook" without a token for a fresh preview.');
363
+ }
364
+ pendingAzureHook = null;
365
+ const authorization = await sqa.createApiToken(label, new Date(Date.now() + API_TOKEN_DAYS * 86400000).toISOString());
366
+ const made = [];
367
+ for (const eventType of missing) {
368
+ try {
369
+ await azure.createServiceHook({ eventType, projectId: projectGuid, url, authorization });
370
+ made.push(eventType);
371
+ }
372
+ catch (e) {
373
+ if (e instanceof ExternalError && (e.status === 401 || e.status === 403)) {
374
+ return ok(`Azure DevOps refused${made.length ? ` after registering ${made.join(', ')}` : ''}: service hooks need a project administrator and a PAT with the Service Hooks scope.\n\n${azureHookInstructions(url, d.externalProject)}`, { registered: made.length > 0, url });
375
+ }
376
+ throw e;
377
+ }
378
+ }
379
+ return ok(`**Registered** Azure DevOps service hooks for ${d.externalProject} → ${url}: ${made.join(', ')}. Work item changes now reach SimplifyQA without a manual sync. They authenticate with the new SimplifyQA API token "${label}".`, { registered: true, url });
380
+ }
381
+ async function webhook(confirmToken) {
382
+ const d = needDiscovery();
383
+ const { adapter, ctx, projectId } = await context();
384
+ await requirePrivilege(adapter, projectId);
385
+ const sqa = sqaClient(ctx);
386
+ const customerId = await sqa.tokenCustomerId();
387
+ if (customerId === null)
388
+ throw new Error('Could not read the SimplifyQA customer of this session. Reconnect and try again.');
389
+ if (d.tool === 'azure')
390
+ return azureHook(confirmToken, d, ctx, sqa, projectId, customerId);
391
+ const projectKey = d.ext.projectKey || d.externalProject;
392
+ const url = webhookUrl(ctx.baseUrl, customerId, projectKey);
393
+ const jira = external('jira');
394
+ let hooks;
395
+ try {
396
+ hooks = await jira.webhooks();
397
+ }
398
+ catch (e) {
399
+ if (e instanceof ExternalError && (e.status === 401 || e.status === 403)) {
400
+ return ok(`The Jira token cannot manage webhooks: that needs the Jira administrator permission.\n\n${webhookInstructions(url, projectKey)}`, { registered: false, url });
401
+ }
402
+ throw e;
403
+ }
404
+ const match = hooks.find((h) => h.url === url);
405
+ if (match)
406
+ return ok(`The Jira webhook is already registered: "${match.name ?? url}"${match.enabled === false ? ' but **disabled**: enable it in Jira settings → System → WebHooks' : ''}.\nURL: ${url}`, { registered: true, enabled: match.enabled !== false, url });
407
+ const name = `SimplifyQA ${projectKey} (customer ${customerId})`;
408
+ if (!confirmToken) {
409
+ pendingWebhook = { token: `w_${digestOf(url).slice(0, 8)}`, url, expires: Date.now() + CONFIRM_TTL_MS };
410
+ return ok(`**Register a Jira webhook** so Jira changes reach SimplifyQA right away:\n- Name: ${name}\n- URL: ${url}\n- Events: ${WEBHOOK_EVENTS.join(', ')}\n- JQL: project = ${projectKey}\n\n**Nothing has been registered.** If the user agrees, call integration_config action "webhook" again with confirmToken "${pendingWebhook.token}" (valid 10 minutes).`, { registered: false, url, confirmToken: pendingWebhook.token });
411
+ }
412
+ const p = pendingWebhook;
413
+ if (!p || p.token !== confirmToken || p.url !== url)
414
+ throw new Error('Unknown confirm token. Call integration_config action "webhook" without a token for a fresh preview.');
415
+ if (Date.now() > p.expires) {
416
+ pendingWebhook = null;
417
+ throw new Error('The confirm token expired. Call integration_config action "webhook" without a token for a fresh preview.');
418
+ }
419
+ pendingWebhook = null;
420
+ try {
421
+ await jira.createWebhook({ name, url, events: WEBHOOK_EVENTS, filters: { 'issue-related-events-section': `project = ${projectKey}` }, excludeBody: false });
422
+ }
423
+ catch (e) {
424
+ if (e instanceof ExternalError && (e.status === 401 || e.status === 403)) {
425
+ return ok(`Jira refused: registering webhooks needs the Jira administrator permission.\n\n${webhookInstructions(url, projectKey)}`, { registered: false, url });
426
+ }
427
+ throw e;
428
+ }
429
+ return ok(`**Registered** the Jira webhook "${name}" → ${url}. New and changed ${projectKey} issues now reach SimplifyQA without a manual sync.`, { registered: true, url });
430
+ }
431
+ function setup(tool) {
432
+ const r = (deps.openTerminal ?? openSetupTerminal)(tool, env);
433
+ const name = TOOLS[tool].name;
434
+ if (!r.opened) {
435
+ return ok(`Ask the user to run this once in their own terminal window (it asks for the tokens with hidden input, so it cannot run through the chat):
436
+
437
+ ${r.command}
438
+
439
+ When it says "Saved", call integration_config with action "status".`, { opened: false, command: r.command });
440
+ }
441
+ return ok(`A terminal window "Simplify3x Connect ${tool} setup" has opened on the user's computer. Tell the user to switch to it and answer the questions there: ${name} site, email, ${name} token (typed hidden) and an optional default SimplifyQA user email. It checks them and saves them to ${credentialsPath(tool, env)}. No SimplifyQA token is asked for: saving a configuration creates one for the user. Never ask for the tokens in chat. When the user says it printed "Saved", call integration_config with action "status"; no reconnect is needed. If no window appeared, they can run: ${r.command}`, { opened: true, command: r.command });
442
+ }
443
+ server.registerTool('integration_config', {
444
+ title: 'Integration configuration',
445
+ description: 'The Jira / Azure DevOps integration configuration of the active SimplifyQA project. action "status" (call first): which credentials are set, active project, discovery, existing configuration, pending save. action "apply" (mappings): save YOUR mapping proposal into the configuration the Marketplace screen edits, after validating it against the discovered metadata (known modules, types and fields; one module per type; each field once; convertible types; required external fields mapped or acknowledged with the user\'s reason). action "delete" (tool): delete the whole configuration (connection and every mapping) like the screen\'s delete; synced records stay; to remove only some modules use apply with type null. action "setup" (tool): when credentials are missing or the user wants to change tokens, open a terminal window on the user\'s computer where THEY type the tokens (hidden); never ask for tokens in chat. action "prepare" (prepare): create what the mapping needs in SimplifyQA — custom fields (TEXT or LIST), list values, releases and sprints; existing ones are reused and close matches are listed as suggestions; run integration_lookup fields first. action "webhook": check that Jira (webhook) or Azure DevOps (service hooks) sends changes to SimplifyQA and register it if missing (needs a Jira admin token, or an Azure project administrator PAT with the Service Hooks scope; otherwise it returns the manual steps). apply, delete, prepare and webhook take TWO STEPS: call WITHOUT confirmToken for a preview and a confirm token (nothing changes); show it to the user; only after the user explicitly agrees, call again with the SAME arguments and the confirmToken.',
446
+ inputSchema: {
447
+ action: z.enum(['status', 'setup', 'apply', 'delete', 'prepare', 'webhook']),
448
+ tool: toolArg.optional().describe('"jira" or "azure"; needed for delete'),
449
+ mappings: mappingSchema.optional(),
450
+ prepare: z.object({
451
+ customFields: z.array(z.object({
452
+ module: z.string(),
453
+ fromField: z.string().optional().describe('Jira / Azure DevOps field key or name to copy: label, type (LIST with its values, else TEXT) and values come from it'),
454
+ label: z.string().optional(),
455
+ type: z.enum(['TEXT', 'LIST']).optional(),
456
+ values: z.array(z.string()).optional(),
457
+ })).optional().describe('SimplifyQA custom fields to add. When the user asks for a Jira / Azure DevOps field that has no SimplifyQA counterpart, pass fromField and the field is created to match it'),
458
+ listValues: z.array(z.object({ module: z.string(), field: z.string().describe('SimplifyQA list field key or label, e.g. state'), values: z.array(z.string()) })).optional().describe('Options to add to SimplifyQA list fields (e.g. Jira statuses or priorities missing in SimplifyQA)'),
459
+ releases: z.array(z.string()).optional().describe('Release names (created for 30 days from today if missing)'),
460
+ sprints: z.array(z.object({ name: z.string(), release: z.string() })).optional().describe('Sprints and their release (created for 14 days from today if missing)'),
461
+ ensureReleaseSprint: z.boolean().optional().describe('If the SimplifyQA project has no release or no sprint, create "Release 1" / "Sprint 1"; existing ones are reported. Use them as the Release / Sprint defaults in apply'),
462
+ }).optional().describe('action "prepare": what to create in SimplifyQA'),
463
+ confirmToken: z.string().optional(),
464
+ acknowledge: z.string().optional().describe("apply: the user's reason for saving with required external fields unmapped"),
465
+ },
466
+ annotations: { readOnlyHint: false, destructiveHint: true },
467
+ }, guard(async (a) => {
468
+ if (a.action === 'status')
469
+ return status();
470
+ if (a.action === 'setup') {
471
+ if (!a.tool)
472
+ throw new Error('action "setup" needs tool ("jira" or "azure").');
473
+ return setup(a.tool);
474
+ }
475
+ if (a.action === 'prepare') {
476
+ if (!a.prepare)
477
+ throw new Error('action "prepare" needs prepare.');
478
+ return prepare(a.prepare, a.confirmToken);
479
+ }
480
+ if (a.action === 'webhook')
481
+ return webhook(a.confirmToken);
482
+ if (a.action === 'apply') {
483
+ if (!a.mappings)
484
+ throw new Error('action "apply" needs mappings.');
485
+ return apply({ mappings: a.mappings, confirmToken: a.confirmToken, acknowledge: a.acknowledge });
486
+ }
487
+ if (!a.tool)
488
+ throw new Error('action "delete" needs tool ("jira" or "azure").');
489
+ return remove({ tool: a.tool, confirmToken: a.confirmToken });
490
+ }));
491
+ async function resolveSubProject(sqa, projectId, subProject) {
492
+ const list = await sqa.subProjects(projectId);
493
+ const want = subProject.trim().toLowerCase();
494
+ const loose = list.filter((sp) => sp.name.toLowerCase().includes(want));
495
+ const hit = list.find((sp) => sp.id.toLowerCase() === want || sp.name.toLowerCase() === want) ?? (loose.length === 1 ? loose[0] : undefined);
496
+ if (!hit)
497
+ throw new Error(`No sub project "${subProject}" in project ${projectId}. Sub projects: ${list.map((sp) => `${sp.name} (id ${sp.id})`).join(', ') || 'none'}.`);
498
+ return hit;
499
+ }
500
+ async function subProjectList(tool) {
501
+ const { ctx, projectId } = await context();
502
+ if (tool === 'azure') {
503
+ return ok('Azure DevOps has one configuration per project: route records to sub projects by mapping the SimplifyQA field **Sub project** (`subProjectId`) to an Azure field such as Area Path or Team in integration_config apply. List the sub projects with sqa_query (collection "subProjects").', { configurations: [] });
504
+ }
505
+ const configs = await sqaClient(ctx).projectConfigs(tool, projectId);
506
+ const subs = configs.filter((c) => c.subProjectId !== undefined && c.subProjectId !== null);
507
+ const whole = configs.find((c) => c.subProjectId === undefined || c.subProjectId === null);
508
+ const rows = subs.map((c) => [String(c.subProjectId), existingProjectName(tool, c), c.id]);
509
+ const listing = rows.length ? table(['Sub project id', `${TOOLS[tool].name} project`, 'Configuration'], rows) : 'No sub project has a configuration yet.';
510
+ return ok(`${listing}\n\nWhole project: ${whole ? existingProjectName(tool, whole) : 'not configured'}.\nSub project names come from sqa_query (collection "subProjects"); match them by id. Each sub project syncs with its own ${TOOLS[tool].name} project: call integration_lookup with what "fields", tool, externalProject and subProject.`, {
511
+ configurations: subs.map((c) => ({ subProjectId: String(c.subProjectId), project: existingProjectName(tool, c), configId: c.id })),
512
+ wholeProject: whole ? existingProjectName(tool, whole) : null,
513
+ });
514
+ }
515
+ async function discover(tool, externalProject, subProject) {
516
+ const { adapter, ctx, projectId } = await context();
517
+ await requirePrivilege(adapter, projectId);
518
+ state.trace = [];
519
+ state.pending = null;
520
+ const sqa = sqaClient(ctx);
521
+ if (subProject && tool === 'azure')
522
+ throw new Error('Azure DevOps has one configuration per project. Map the whole project, and route records to sub projects by mapping the SimplifyQA field "Sub project" to an Azure field such as Area Path.');
523
+ const sub = subProject ? await resolveSubProject(sqa, projectId, subProject) : null;
524
+ const ext = await external(tool).discover(externalProject);
525
+ const { qa, raw } = await sqa.discover(projectId, tool === 'azure');
526
+ const existing = await sqa.findConfig(tool, projectId, sub?.id ?? null);
527
+ const otherTool = tool === 'azure' ? 'jira' : 'azure';
528
+ const other = existing ? null : await sqa.findConfig(otherTool, projectId);
529
+ state.discovery = { tool, externalProject, projectId, ext, qa, raw, subProjectId: sub?.id ?? null, subProjectName: sub?.name ?? null };
530
+ state.existing = existing;
531
+ state.other = other ? TOOLS[otherTool].name : null;
532
+ const warn = existing && !sameProject(tool, existing, ext)
533
+ ? `\n\n⚠ The current configuration points at ${existingProjectName(tool, existing)}, not ${externalProject}; integration_config apply will refuse until it is removed in the integration screen.`
534
+ : other ? `\n\n⚠ This project already has a ${TOOLS[otherTool].name} integration. A project can have only one (Jira or Azure DevOps); integration_config apply will refuse until it is deleted in Marketplace.` : '';
535
+ return ok(`${sub ? `**Sub project ${sub.name}** (id ${sub.id}) — this lookup and the next apply, webhook, test, sync and logs use its own configuration.\n\n` : ''}${describeDiscovery(tool, ext, qa, existing)}${warn}\n\n_${state.trace.length} REST calls; see integration_logs with kind "calls"._`, {
536
+ tool, projectId, external: ext, simplifyqa: qa, current: describeExisting(tool, existing),
537
+ });
538
+ }
539
+ function fieldValues(field) {
540
+ const d = needDiscovery();
541
+ const want = field.toLowerCase();
542
+ const out = [];
543
+ for (const [type, t] of Object.entries(d.ext.types)) {
544
+ for (const f of t.fields.filter((x) => x.key.toLowerCase() === want || x.name.toLowerCase() === want))
545
+ out.push(`- ${TOOLS[d.tool].name} ${type} · ${f.name} (\`${f.key}\`): ${f.values?.length ? f.values.join(' / ') : 'free value'}`);
546
+ if (/^(status|state)$/.test(want))
547
+ out.push(`- ${TOOLS[d.tool].name} ${type} · statuses: ${t.statuses.map((s) => s.name).join(' / ') || '—'}`);
548
+ }
549
+ for (const m of d.qa) {
550
+ for (const f of m.fields.filter((x) => x.key.toLowerCase() === want || x.label.toLowerCase() === want))
551
+ out.push(`- SimplifyQA ${m.name} · ${f.label} (\`${f.key}\`): ${f.values?.length ? f.values.join(' / ') : 'free value'}`);
552
+ }
553
+ return ok(out.length ? out.join('\n') : `No field "${field}" in the last discovery. Use a field key or name from integration_lookup with what "fields".`);
554
+ }
555
+ server.registerTool('integration_lookup', {
556
+ title: 'Look up integration metadata',
557
+ description: 'Read-only facts for YOUR mapping proposal. what "projects" (tool): the Jira projects where the credentials can create issues, or the Azure DevOps projects the credentials belong to; ask the user which to map, never guess. what "fields" (tool, externalProject): both sides for the active SimplifyQA project — Jira issue types / Azure DevOps work item types with fields (key, type, required, allowed values, sync type) and statuses; every SimplifyQA module the integration screen offers with fields, types, required flags and list values; and the current configuration, which a proposal should start from. Fields whose sync type is "not supported" cannot be mapped. what "subprojects" (tool): which sub project ids of the active project already have a configuration and the Jira project each maps to (names come from sqa_query collection "subProjects"); for Jira each sub project can sync with its own Jira project (pass subProject to "fields"), for Azure DevOps sub projects are routed through the Sub project field. what "values" (field): every allowed value of one field on both sides, from the last "fields" lookup. SimplifyQA projects, sub projects, users, releases, sprints and modules are read with sqa_query, not here. Nothing is written.',
558
+ inputSchema: {
559
+ what: z.enum(['projects', 'subprojects', 'fields', 'values']),
560
+ tool: toolArg.optional().describe('"jira" or "azure"; needed for projects and fields'),
561
+ externalProject: z.string().optional().describe('fields: Jira project key, or Azure DevOps project name'),
562
+ subProject: z.string().optional().describe('fields (Jira): SimplifyQA sub project name or id, to configure that sub project with its own Jira project instead of the whole project'),
563
+ field: z.string().optional().describe('values: field key or name'),
564
+ },
565
+ annotations: { readOnlyHint: true },
566
+ }, guard(async (a) => {
567
+ if (a.what === 'values') {
568
+ if (!a.field)
569
+ throw new Error('what "values" needs field.');
570
+ return fieldValues(a.field);
571
+ }
572
+ if (!a.tool)
573
+ throw new Error(`what "${a.what}" needs tool ("jira" or "azure").`);
574
+ if (a.what === 'projects') {
575
+ const projects = await external(a.tool).projects();
576
+ return ok(table(['Key', 'Name', 'Id', 'Type'], projects.map((p) => [p.key, p.name, p.id, p.type ?? ''])), { projects });
577
+ }
578
+ if (a.what === 'subprojects')
579
+ return subProjectList(a.tool);
580
+ if (!a.externalProject)
581
+ throw new Error('what "fields" needs externalProject.');
582
+ return discover(a.tool, a.externalProject, a.subProject);
583
+ }));
584
+ let pendingSync = null;
585
+ server.registerTool('integration_sync', {
586
+ title: 'Run integration sync',
587
+ description: 'Run the same Jira / Azure DevOps → SimplifyQA sync as the integration screen\'s Sync button, for one mapped issue / work item type of the active project. With test: true it instead runs a TWO-WAY TEST: it creates a marked test issue / work item in Jira or Azure DevOps and checks it arrives in SimplifyQA, creates a test Defect in SimplifyQA and checks it arrives on the other side, then deletes all of them; use it after saving, fix what fails and test again. TWO STEPS: call WITHOUT confirmToken to check the SAVED configuration (every mandatory SimplifyQA field of that module must be mapped or have a default, or record creation fails) and get a confirm token; only after the user explicitly says to run it, call again with the token. The sync runs in the background and writes records into SimplifyQA; read the outcome with integration_logs.',
588
+ inputSchema: {
589
+ type: z.string().describe('The mapped Jira issue type / Azure DevOps work item type, e.g. "Bug1"'),
590
+ test: z.boolean().optional().describe('Run the two-way test instead of a full sync'),
591
+ confirmToken: z.string().optional(),
592
+ },
593
+ annotations: { readOnlyHint: false, destructiveHint: true },
594
+ }, guard(async (a) => {
595
+ const d = needDiscovery();
596
+ const test = a.test === true;
597
+ const { adapter, ctx, projectId } = await context();
598
+ if (projectId !== d.projectId)
599
+ throw new Error(`The active project changed to ${projectId} since discovery (${d.projectId}). Run integration_lookup with what "fields" again.`);
600
+ await requirePrivilege(adapter, projectId);
601
+ const sqa = sqaClient(ctx);
602
+ const config = await sqa.findConfig(d.tool, projectId, d.subProjectId);
603
+ if (!config)
604
+ throw new Error(`Project ${projectId}${d.subProjectName ? ` · sub project ${d.subProjectName}` : ''} has no ${TOOLS[d.tool].name} configuration yet. Save one with integration_config action "apply" first.`);
605
+ const type = Object.keys(config.issueMap ?? {}).find((t) => t.toLowerCase() === a.type.toLowerCase());
606
+ if (!type)
607
+ throw new Error(`"${a.type}" is not mapped in the saved configuration. Mapped: ${Object.keys(config.issueMap ?? {}).join(', ') || 'none'}.`);
608
+ const modKey = config.issueMap[type];
609
+ const K = TOOLS[d.tool].keyField;
610
+ const entries = config.fieldsMap?.[`${modKey}__${type}`] ?? [];
611
+ const covered = new Set(entries.filter((e) => e[K] || e['default']).map((e) => String(e['qaKey'])));
612
+ const mod = d.qa.find((m) => m.key === modKey);
613
+ const gaps = (mod?.fields ?? []).filter((f) => f.required && !covered.has(f.key)).map((f) => f.label);
614
+ const summary = `${TOOLS[d.tool].name} ${type} → SimplifyQA ${mod?.name ?? modKey} in project ${projectId} (configuration ${config.id}).`;
615
+ if (gaps.length) {
616
+ pendingSync = null;
617
+ return ok(`${summary}\n\n**Not ready — records would fail to create.** Mandatory SimplifyQA fields with neither a mapping nor a default: ${gaps.join(', ')}.\nAdd a mapping or a \`default\` for each with integration_config action "apply", then try again.`, { ready: false, gaps });
618
+ }
619
+ if (test && !a.confirmToken) {
620
+ pendingSync = { token: `t_${Math.random().toString(36).slice(2, 10)}`, type, configId: config.id, expires: Date.now() + CONFIRM_TTL_MS, test };
621
+ return ok(`${summary}\n\n**Two-way test** (nothing has run yet):\n1. Create a test ${type} "[MCP sync test] …" in ${TOOLS[d.tool].name} project ${d.externalProject} with a dummy value in every mapped field, wait for it in SimplifyQA and check each field arrived.\n2. ${modKey === 'defect' ? `Create a SimplifyQA Defect "[MCP sync test] … (SQA)" with a dummy value in every mapped field, wait for it in ${TOOLS[d.tool].name} and check each field arrived.` : `Skipped: SimplifyQA test records are created for Defect only (${type} is mapped to ${modKey}).`}\n3. Delete every test record on both sides.\n4. If both directions pass, start the full sync of every ${type} (as the Sync button does).\nIf the user agrees, call integration_sync again with type "${type}", test true and confirmToken "${pendingSync.token}" (valid 10 minutes).`, { ready: true, confirmToken: pendingSync.token });
622
+ }
623
+ if (!a.confirmToken) {
624
+ pendingSync = { token: `s_${Math.random().toString(36).slice(2, 10)}`, type, configId: config.id, expires: Date.now() + CONFIRM_TTL_MS, test };
625
+ return ok(`${summary}\n\nReady: every mandatory SimplifyQA field is mapped or defaulted.\n**Nothing has run.** This pulls every ${type} in ${d.externalProject} into SimplifyQA and pushes changes back, as the Sync button does. If the user agrees, call integration_sync again with confirmToken "${pendingSync.token}" (valid 10 minutes).`, { ready: true, confirmToken: pendingSync.token });
626
+ }
627
+ const p = pendingSync;
628
+ if (!p || p.token !== a.confirmToken || p.type !== type || p.configId !== config.id || p.test !== test)
629
+ throw new Error('Unknown confirm token. Call integration_sync without a token for a fresh check.');
630
+ if (Date.now() > p.expires) {
631
+ pendingSync = null;
632
+ throw new Error('The confirm token expired. Call integration_sync without a token for a fresh check.');
633
+ }
634
+ pendingSync = null;
635
+ if (test) {
636
+ const target = d.tool === 'azure' ? azureTarget(external('azure'), d.externalProject) : jiraTarget(external('jira'), d.ext.projectKey || d.externalProject);
637
+ const { steps, cleanup } = await runTwoWayTest({
638
+ target, tool: d.tool, sqa, extDiscovery: d.ext, rawFields: d.raw[modKey]?.fields ?? [], config, projectId, type, modKey, userId: ctx.userId ? Number(ctx.userId) : null,
639
+ stamp: new Date().toISOString().slice(0, 16).replace('T', ' '),
640
+ timeoutMs: deps.testTimeoutMs ?? 60000, intervalMs: deps.testIntervalMs ?? 5000,
641
+ wait: deps.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
642
+ });
643
+ const passed = steps.length > 0 && steps.every((s) => s.ok);
644
+ let syncLine = '\n\n**Full sync not started.** Fix the cause (integration_logs shows the sync errors; integration_config action "webhook" checks the webhook; prepare / apply fix fields and values), then run the test again.';
645
+ let syncStarted = false;
646
+ if (passed) {
647
+ try {
648
+ const r = await sqa.startSync(d.tool, config.id, type);
649
+ syncStarted = true;
650
+ syncLine = `\n\n**Full sync started** for ${type}: ${r.message ?? 'running in the background'}. Read the outcome with integration_logs after a minute.`;
651
+ }
652
+ catch (e) {
653
+ syncLine = `\n\n**The test passed but the full sync could not start:** ${e instanceof Error ? e.message : String(e)}`;
654
+ }
655
+ }
656
+ return ok(`**Two-way test ${passed ? 'passed' : 'did not pass'}**\n${steps.map((s) => `- ${s.ok ? '✓' : '✗'} ${s.direction}: ${s.detail}`).join('\n')}\n\n**Clean-up**\n${cleanup.map((c) => `- ${c}`).join('\n') || '- nothing was created'}${syncLine}`, { passed, steps, cleanup, syncStarted });
657
+ }
658
+ const r = await sqa.startSync(d.tool, config.id, type);
659
+ return ok(`**Sync started** for ${type}: ${r.message ?? 'running in the background'}.\nIt runs on the server; check progress in Marketplace → ${TOOLS[d.tool].name}, and read errors with integration_logs after a minute.`, { started: true });
660
+ }));
661
+ server.registerTool('integration_logs', {
662
+ title: 'Integration logs',
663
+ description: 'kind "sync" (default): the latest sync log lines and sync errors for the active project\'s Jira / Azure DevOps integration (the same log the integration screen downloads, and the per-record errors); tokens are removed. kind "calls": the REST calls made by the last lookup or save (system, path, status, ms, item count).',
664
+ inputSchema: {
665
+ kind: z.enum(['sync', 'calls']).optional(),
666
+ lines: z.number().int().min(10).max(500).optional().describe('sync: how many log lines from the end (default 80)'),
667
+ },
668
+ annotations: { readOnlyHint: true },
669
+ }, guard(async (a) => {
670
+ if (a.kind === 'calls')
671
+ return ok(state.trace.length ? table(['System', 'Call', 'Status', 'ms', 'Items'], state.trace.map((t) => [t.system, `${t.method} ${t.path}`, t.status, t.ms, t.count ?? ''])) : 'No calls made yet.');
672
+ const d = needDiscovery();
673
+ const { ctx, projectId } = await context();
674
+ const sqa = sqaClient(ctx);
675
+ const config = await sqa.findConfig(d.tool, projectId, d.subProjectId);
676
+ const customerId = Number(config?.['customerId']);
677
+ const scrub = (s) => s.replace(/(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/g, '$1 <redacted>').replace(/("?(?:apiToken|sqaToken|token|password|authorization)"?\s*[:=]\s*)"[^"]*"/gi, '$1"<redacted>"');
678
+ const parts = [];
679
+ if (d.tool === 'jira' && Number.isFinite(customerId)) {
680
+ const log = await sqa.syncLogFile(customerId, projectId);
681
+ const tail = log ? log.split(/\r?\n/).filter(Boolean).slice(-(a.lines ?? 80)) : [];
682
+ parts.push(`### Sync log (last ${tail.length} lines)`, tail.length ? '```\n' + scrub(tail.join('\n')) + '\n```' : 'No sync log yet for this project: no sync has run.');
683
+ }
684
+ const errors = await sqa.syncErrors(d.tool, projectId, 20);
685
+ if (d.tool === 'azure') {
686
+ parts.push(`### Recent sync records, newest first (${errors.length})`);
687
+ for (const e of errors) {
688
+ const call = e['httpMethod'] ? `${String(e['httpMethod'])} ${String(e['httpUrl'] ?? '')} → ${String(e['httpStatus'] ?? '')}` : '';
689
+ const message = e['errorMessages'] ? JSON.stringify(e['errorMessages']) : e['apilogs']?.message ?? '';
690
+ const cells = [e['createdAt'], e['direction'], e['collection'], e['externalId'] ? `work item ${String(e['externalId'])}` : '', call, e['outcome'], message];
691
+ parts.push(`- ${scrub(cells.filter((x) => x !== undefined && x !== null && x !== '').map(String).join(' · ')).slice(0, 600)}`);
692
+ }
693
+ }
694
+ else {
695
+ parts.push(`### Sync errors (${errors.length})`);
696
+ for (const e of errors)
697
+ parts.push(`- ${scrub(JSON.stringify({ sqaId: e['sqaId'], jiraId: e['jiraId'], error: e['error'] ?? e['errorMessages'] ?? e['apilogs'] })).slice(0, 600)}`);
698
+ }
699
+ if (!errors.length)
700
+ parts.push('None recorded.');
701
+ return ok(parts.join('\n'));
702
+ }));
703
+ }
704
+ //# sourceMappingURL=integration.tools.js.map