@smartbear/mcp 0.35.0 → 0.37.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.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/dist/bearq/tool/tasks/wait-for-task.js +3 -3
  3. package/dist/bugsnag/client.js +1 -1
  4. package/dist/bugsnag/tool/error/get-error.js +1 -1
  5. package/dist/bugsnag/tool/error/list-project-errors.js +1 -1
  6. package/dist/bugsnag/tool/error/update-error.js +1 -1
  7. package/dist/bugsnag/tool/event/get-event-details-from-dashboard-url.js +1 -1
  8. package/dist/bugsnag/tool/event/get-event.js +1 -1
  9. package/dist/bugsnag/tool/event/list-error-events.js +1 -1
  10. package/dist/bugsnag/tool/performance/get-network-endpoint-groupings.js +1 -1
  11. package/dist/bugsnag/tool/performance/get-span-group.js +1 -1
  12. package/dist/bugsnag/tool/performance/get-trace.js +1 -1
  13. package/dist/bugsnag/tool/performance/list-span-groups.js +1 -1
  14. package/dist/bugsnag/tool/performance/list-spans.js +1 -1
  15. package/dist/bugsnag/tool/performance/list-trace-fields.js +1 -1
  16. package/dist/bugsnag/tool/performance/set-network-endpoint-groupings.js +1 -1
  17. package/dist/bugsnag/tool/project/get-current-project.js +1 -1
  18. package/dist/bugsnag/tool/project/list-project-event-filters.js +1 -1
  19. package/dist/bugsnag/tool/project/list-projects.js +1 -1
  20. package/dist/bugsnag/tool/release/get-build.js +1 -1
  21. package/dist/bugsnag/tool/release/get-release.js +1 -1
  22. package/dist/bugsnag/tool/release/list-releases.js +1 -1
  23. package/dist/collaborator/client.js +10 -10
  24. package/dist/common/server.js +11 -32
  25. package/dist/common/transport-http.js +5 -5
  26. package/dist/common/transport-stdio.js +1 -1
  27. package/dist/common/zod-utils.js +2 -1
  28. package/dist/package.json.js +1 -1
  29. package/dist/pactflow/client/base.js +8 -4
  30. package/dist/pactflow/client/tools.js +2 -2
  31. package/dist/pactflow/client.js +4 -4
  32. package/dist/qmetry/client/auto-resolve.js +5 -0
  33. package/dist/qmetry/client/date-utils.js +104 -0
  34. package/dist/qmetry/client/handlers.js +9 -5
  35. package/dist/qmetry/client/issues.js +124 -7
  36. package/dist/qmetry/client/testcase.js +36 -2
  37. package/dist/qmetry/client/testsuite.js +27 -2
  38. package/dist/qmetry/client/tools/issue-tools.js +202 -23
  39. package/dist/qmetry/client/tools/project-tools.js +14 -2
  40. package/dist/qmetry/client/tools/testcase-tools.js +275 -14
  41. package/dist/qmetry/client/tools/testsuite-tools.js +152 -5
  42. package/dist/qmetry/client/tools/udf-tools.js +83 -5
  43. package/dist/qmetry/client/udf.js +159 -4
  44. package/dist/qmetry/client.js +236 -1
  45. package/dist/qmetry/config/constants.js +5 -1
  46. package/dist/qmetry/config/rest-endpoints.js +7 -3
  47. package/dist/qmetry/types/common.js +113 -12
  48. package/dist/qmetry/types/testcase.js +1 -2
  49. package/dist/qmetry/types/udf.js +12 -1
  50. package/dist/reflect/tool/recording/connect-to-session.js +2 -2
  51. package/dist/swagger/client/api.js +96 -12
  52. package/dist/swagger/client/functional-testing-api.js +7 -1
  53. package/dist/swagger/client/functional-testing-tools.js +20 -17
  54. package/dist/swagger/client/functional-testing-types.js +184 -1
  55. package/dist/swagger/client/patch-spec-utils.js +31 -0
  56. package/dist/swagger/client/portal-types.js +1 -1
  57. package/dist/swagger/client/registry-types.js +44 -0
  58. package/dist/swagger/client/tools.js +11 -2
  59. package/dist/swagger/client/utils.js +8 -0
  60. package/dist/swagger/client.js +6 -2
  61. package/dist/zephyr/common/rest-api-schemas.js +3748 -3698
  62. package/dist/zephyr/tool/test-case/create-issue-link.js +4 -2
  63. package/dist/zephyr/tool/test-case/create-test-script.js +4 -2
  64. package/dist/zephyr/tool/test-case/create-test-steps.js +5 -1
  65. package/dist/zephyr/tool/test-case/get-test-steps.js +4 -2
  66. package/dist/zephyr/tool/test-case/update-test-case.js +3 -1
  67. package/dist/zephyr/tool/test-cycle/create-issue-link.js +4 -2
  68. package/dist/zephyr/tool/test-cycle/create-web-link.js +4 -2
  69. package/dist/zephyr/tool/test-cycle/update-test-cycle.js +5 -1
  70. package/dist/zephyr/tool/test-execution/create-issue-link.js +4 -2
  71. package/dist/zephyr/tool/test-execution/get-test-steps.js +4 -2
  72. package/dist/zephyr/tool/test-execution/update-test-execution.js +4 -2
  73. package/dist/zephyr/tool/test-execution/update-test-steps.js +4 -2
  74. package/package.json +7 -2
@@ -220,12 +220,25 @@ const UpdateCycleArgsSchema = z.object({
220
220
  )
221
221
  })
222
222
  });
223
+ const StepUdfValueSchema = z.union([
224
+ z.string(),
225
+ z.number(),
226
+ z.array(z.number()),
227
+ z.object({ parent: z.number(), child: z.number().optional() }),
228
+ z.object({ ADD: z.array(z.unknown()), REMOVE: z.array(z.unknown()) }),
229
+ // Step cascade _value array: [{ FieldID, FieldValue: [{id, value, child: {id, value}}], type }]
230
+ z.array(z.record(z.string(), z.unknown())),
231
+ // Step cascade _selectedList: { id: udfmID, name: fieldName, type: 'CASCADINGLIST' }
232
+ z.record(z.string(), z.unknown())
233
+ ]);
223
234
  const CreateTestCaseStepSchema = z.object({
224
235
  orderId: z.number(),
225
236
  description: z.string(),
226
237
  inputData: z.string().optional(),
227
238
  expectedOutcome: z.string().optional(),
228
- UDF: z.record(z.string(), z.string()).optional(),
239
+ UDF: z.record(z.string(), StepUdfValueSchema).optional().describe(
240
+ "Step-level UDF values. Keys = UDF field names. Values depend on field type: STRING/LARGETEXT: string, NUMBER: number, DATETIMEPICKER: date string (DD-MM-YYYY), LOOKUPLIST: numeric ID, MULTILOOKUPLIST: array of IDs. CASCADINGLIST requires THREE sibling keys in this UDF object — e.g. for field 'proj': proj: {parent: parentId, child: childId}, proj_value: [{FieldID:'proj', FieldValue:[{id:parentId, value:'parentLabel', child:{id:childId, value:'childLabel'}}], type:'CASCADINGLIST'}], proj_selectedList: {id: udfmID, name:'proj', type:'CASCADINGLIST'}. Get parentLabel/childLabel from Fetch Cascade Child Values. Get udfmID from Fetch UDF Layout stepFields[].projectUserFieldID."
241
+ ),
229
242
  tcStepID: z.number().optional()
230
243
  // Required for updating existing steps, omit for new steps
231
244
  });
@@ -240,22 +253,55 @@ const UpdateTestCaseRemoveStepSchema = z.object({
240
253
  description: z.string(),
241
254
  inputData: z.string().optional(),
242
255
  expectedOutcome: z.string().optional(),
243
- UDF: z.record(z.string(), z.string()).optional(),
256
+ UDF: z.record(z.string(), StepUdfValueSchema).optional(),
244
257
  tcsIsShared: z.boolean(),
245
258
  tcsIsParameterized: z.boolean()
246
259
  });
260
+ const UdfWrapperFieldSchema = z.object({
261
+ fieldID: z.number().int().positive().describe(
262
+ "Numeric field ID (projectUserFieldID) from 'Fetch UDF Layout' with pageName='DETAIL'. Required for update UDF wrapper."
263
+ ),
264
+ value: z.union([
265
+ z.string(),
266
+ z.number(),
267
+ z.array(z.number().int()),
268
+ z.object({
269
+ parent: z.number().int(),
270
+ child: z.number().int().optional()
271
+ }),
272
+ z.null()
273
+ ]).describe(
274
+ "UDF value. Type depends on fieldTypeName: STRING/LARGETEXT: string, NUMBER: number, DATETIMEPICKER: 'MM-DD-YYYY' or 'DD-MM-YYYY', LOOKUPLIST: numeric ID, MULTILOOKUPLIST: array of IDs, CASCADINGLIST: { parent, child }."
275
+ )
276
+ });
277
+ const UdfFieldsSchema = z.record(
278
+ z.string(),
279
+ z.union([
280
+ z.string(),
281
+ z.number(),
282
+ z.array(z.number()),
283
+ z.object({ parent: z.number(), child: z.number().optional() }),
284
+ z.null()
285
+ ])
286
+ ).optional().describe(
287
+ "Flat UDF field values. Keys = UDF field names from 'Fetch UDF Layout'. Values depend on fieldTypeName: STRING/LARGETEXT: string, NUMBER: number, DATETIMEPICKER: date string ('14-08-2026'), LOOKUPLIST: numeric ID, MULTILOOKUPLIST: array of IDs [101, 102], CASCADINGLIST: { parent: 101, child: 102 }. Call 'Fetch UDF Layout' with entityType + pageName='ADD' to discover available fields and list option IDs."
288
+ );
247
289
  const CreateTestCaseArgsSchema = z.object({
248
290
  tcFolderID: z.string().optional().describe(
249
291
  "Test Case folder ID - SYSTEM AUTOMATICALLY RESOLVES THIS. Leave empty unless you have a specific folder ID. System will fetch project info using the projectKey and extract rootFolders.TC.id automatically. Manual folder ID only needed if you want to target a specific sub-folder."
250
292
  ),
251
- steps: z.array(CreateTestCaseStepSchema).optional(),
293
+ steps: z.array(CreateTestCaseStepSchema).optional().describe(
294
+ "STEPS INCLUSION RULE — read before deciding whether to include this field:\n\nDEFAULT BEHAVIOR: OMIT 'steps' entirely from the payload. Do NOT include steps: [] (empty array).\nA test case without steps is valid and is the normal case when the user did not mention steps.\n\nINCLUDE 'steps' ONLY in these two scenarios:\n SCENARIO 1 — User explicitly mentions steps in their prompt.\n Examples: 'create test case with steps', 'step 1: open browser, step 2: click login',\n 'add these steps: ...', 'include steps', 'create with following steps'.\n When user provides step text, parse each step into { orderId, description, inputData?, expectedOutcome? }.\n\n SCENARIO 2 — Any field in 'stepSystemFields' OR 'stepFields' from Fetch UDF Layout has isMandatory=true.\n stepSystemFields = built-in step fields (description, expectedOutcome, etc.).\n stepFields = step-level UDF fields (custom fields configured per project).\n If EITHER array has isMandatory=true on any entry, the backend REQUIRES at least 1 step.\n In this case you MUST include at least 1 step even if the user did not mention steps.\n Also fill mandatory step UDF fields from stepFields in step.UDF — use stepDefaultValues if defaults exist, else placeholder.\n Ask the user for step content OR create a placeholder step with description='Step 1'.\n\nNEVER include 'steps' in any other scenario — omitting it keeps the payload clean and avoids BE errors.\nNEVER send steps: [] (empty array) — either omit the field or send at least 1 valid step object.\n\nStep object fields:\n orderId (required): sequential integer starting at 1\n description (required): step action text\n inputData (optional): test data for this step\n expectedOutcome (optional): what should happen after this step\n UDF (optional): step-level custom fields\n tcStepID (omit on create — only used when updating existing steps)"
295
+ ),
252
296
  name: z.string(),
253
297
  priority: z.number().optional(),
254
298
  component: z.array(z.number()).optional(),
255
299
  testcaseOwner: z.number().optional(),
256
300
  testCaseState: z.number().optional(),
257
301
  testCaseType: z.number().optional(),
258
- estimatedTime: z.number().optional(),
302
+ estimatedTime: z.number().optional().describe(
303
+ "Estimated execution time in SECONDS (e.g. 3600 = 1 hour, 36000 = 10 hours). NOT minutes."
304
+ ),
259
305
  testingType: z.number().optional(),
260
306
  description: z.string().optional(),
261
307
  associateRelCyc: z.boolean().optional(),
@@ -263,9 +309,12 @@ const CreateTestCaseArgsSchema = z.object({
263
309
  z.object({
264
310
  release: z.number(),
265
311
  cycle: z.array(z.number()),
266
- version: z.number().optional()
312
+ version: z.number().optional().default(1)
267
313
  })
268
- ).optional()
314
+ ).optional().describe(
315
+ "Release/cycle mapping. Set associateRelCyc=true when providing this. version field defaults to 1 if not specified."
316
+ ),
317
+ udfFields: UdfFieldsSchema
269
318
  });
270
319
  const UpdateTestCaseArgsSchema = z.object({
271
320
  projectKey: CommonFields.projectKeyOptional,
@@ -306,6 +355,10 @@ const UpdateTestCaseArgsSchema = z.object({
306
355
  description: z.string().optional(),
307
356
  updateOnlyMetadata: z.boolean().optional().describe(
308
357
  "Set to true to update only metadata fields without touching test steps. When true, steps and removeSteps are ignored."
358
+ ),
359
+ udfFields: UdfFieldsSchema,
360
+ UDF: z.record(z.string(), UdfWrapperFieldSchema).optional().describe(
361
+ "UDF wrapper required for update operations. Keys = UDF field names. Each value must include fieldID (from 'Fetch UDF Layout' with pageName='DETAIL') and value. Also set matching flat key in udfFields for the LOOKUPLIST Alias display. Example: { custom_text: { fieldID: 1001, value: 'new value' } }"
309
362
  )
310
363
  });
311
364
  const TestCaseListArgsSchema = z.object({
@@ -351,6 +404,16 @@ const TestCaseStepsArgsSchema = z.object({
351
404
  page: CommonFields.page,
352
405
  limit: CommonFields.limit
353
406
  });
407
+ const TestCaseStepsWithUdfArgsSchema = z.object({
408
+ projectKey: CommonFields.projectKeyOptional,
409
+ baseUrl: CommonFields.baseUrl,
410
+ tcID: CommonFields.tcID,
411
+ viewId: CommonFields.tcViewId,
412
+ version: CommonFields.versionOptional,
413
+ start: CommonFields.start,
414
+ page: CommonFields.page,
415
+ limit: CommonFields.limit
416
+ });
354
417
  const TestCaseExecutionsArgsSchema = z.object({
355
418
  projectKey: CommonFields.projectKeyOptional,
356
419
  baseUrl: CommonFields.baseUrl,
@@ -447,10 +510,17 @@ const CreateTestSuiteArgsSchema = z.object({
447
510
  associateRelCyc: z.boolean().optional(),
448
511
  releaseCycleMapping: z.array(
449
512
  z.object({
450
- buildID: z.number(),
451
- releaseId: z.number()
513
+ releaseId: z.number().describe(
514
+ "Release numeric ID. CRITICAL: key is 'releaseId' (lowercase d) — do NOT use 'releaseID', 'release', or 'releaseKey'. Get from project info → projects[<index>].releases[<index>].releaseID. NEVER use the TC mapping key 'release' here — test suite mapping uses 'releaseId'."
515
+ ),
516
+ buildID: z.number().describe(
517
+ "Cycle/Build numeric ID. CRITICAL: key is 'buildID' (capital D) — do NOT use 'cycleId', 'cycle', 'buildId', or 'cycleID'. Get from project info → projects[<index>].releases[<index>].builds[<index>].buildID. NEVER use the TC mapping key 'cycle' here — test suite mapping uses 'buildID'."
518
+ )
452
519
  })
453
- ).optional()
520
+ ).optional().describe(
521
+ "Release/cycle association for the test suite. CRITICAL SHAPE DIFFERENCE vs Test Case mapping: Test Suite uses: { releaseId: number, buildID: number } Test Case uses: { release: number, cycle: number[], version: number } — DO NOT use TC shape here. Set associateRelCyc=true when providing this array. Example: [{ releaseId: 92112, buildID: 130831 }]"
522
+ ),
523
+ udfFields: UdfFieldsSchema
454
524
  });
455
525
  const UpdateTestSuiteArgsSchema = z.object({
456
526
  id: z.number().describe("Id of Test Suite to be updated (required)"),
@@ -461,7 +531,11 @@ const UpdateTestSuiteArgsSchema = z.object({
461
531
  name: z.string().optional().describe("Name of the Test Suite"),
462
532
  description: z.string().optional().describe("Description of the Test Suite"),
463
533
  testsuiteOwner: z.number().optional().describe("Owner ID of the Test Suite"),
464
- testSuiteState: z.number().optional().describe("State of the Test Suite")
534
+ testSuiteState: z.number().optional().describe("State of the Test Suite"),
535
+ udfFields: UdfFieldsSchema,
536
+ UDF: z.record(z.string(), UdfWrapperFieldSchema).optional().describe(
537
+ "UDF wrapper required for update. Keys = UDF field names. Each value must include fieldID (from 'Fetch UDF Layout' with pageName='DETAIL') and value."
538
+ )
465
539
  });
466
540
  const TestSuiteListArgsSchema = z.object({
467
541
  projectKey: CommonFields.projectKeyOptional,
@@ -479,6 +553,19 @@ const TestSuiteListArgsSchema = z.object({
479
553
  "Sort Records - refer json schema, Possible property - entityKey, name, testsuiteStatus, linkedPlatformCount, linkedTcCount, createdDate, createdByAlias, updatedDate, updatedByAlias, attachmentCount, owner, remExecutionTime, totalExecutionTime"
480
554
  ).default('[{"property":"name","direction":"ASC"}]')
481
555
  });
556
+ const FetchTestSuiteDetailsArgsSchema = z.object({
557
+ projectKey: CommonFields.projectKeyOptional,
558
+ baseUrl: CommonFields.baseUrl,
559
+ id: z.number().int().positive().describe("Test Suite ID (numeric ID)"),
560
+ scope: CommonFields.scope
561
+ });
562
+ const FetchIssueDetailsArgsSchema = z.object({
563
+ projectKey: CommonFields.projectKeyOptional,
564
+ baseUrl: CommonFields.baseUrl,
565
+ defectId: z.number().int().positive().describe(
566
+ "Issue DefectId (numeric ID) — use data[<index>].id from Fetch Issues/Defects response. The field in the list API response is named 'id', not 'DefectId'."
567
+ )
568
+ });
482
569
  const TestSuitesForTestCaseArgsSchema = z.object({
483
570
  projectKey: CommonFields.projectKeyOptional,
484
571
  baseUrl: CommonFields.baseUrl,
@@ -583,7 +670,14 @@ const CreateIssueArgsSchema = z.object({
583
670
  affectedCycles: z.array(z.number()).optional().describe("Cycle IDs affected by this issue"),
584
671
  tcRunID: z.number().optional().describe(
585
672
  "Test Case Run ID to link this defect/issue to a test execution (optional)"
586
- )
673
+ ),
674
+ environment: z.string().optional().describe(
675
+ "Environment where the issue was found (e.g. 'Chrome', 'Firefox', 'Production'). Free-text string — no ID lookup needed."
676
+ ),
677
+ issueState: z.number().optional().describe(
678
+ "Issue status ID. Optional by default — QMetry allows admins to make this mandatory at the project level. Get valid IDs from project info → customListObjs.issueState[index].id. Common values: Open, Reopened, Resolved, Closed."
679
+ ),
680
+ udfFields: UdfFieldsSchema
587
681
  });
588
682
  const UpdateIssueArgsSchema = z.object({
589
683
  DefectId: z.coerce.number().describe(
@@ -596,7 +690,11 @@ const UpdateIssueArgsSchema = z.object({
596
690
  description: z.string().optional().describe("Detailed description of the defect/issue"),
597
691
  issueOwner: z.number().optional().describe("Owner/user ID for the issue"),
598
692
  affectedRelease: z.number().optional().describe("Release IDs affected by this issue"),
599
- affectedCycles: z.number().optional().describe("Cycle IDs affected by this issue")
693
+ affectedCycles: z.number().optional().describe("Cycle IDs affected by this issue"),
694
+ udfFields: UdfFieldsSchema,
695
+ UDF: z.record(z.string(), UdfWrapperFieldSchema).optional().describe(
696
+ "UDF wrapper required for update. Keys = UDF field names. Each value must include fieldID (from 'Fetch UDF Layout' with pageName='DETAIL') and value."
697
+ )
600
698
  });
601
699
  const IssuesListArgsSchema = z.object({
602
700
  projectKey: CommonFields.projectKeyOptional,
@@ -784,6 +882,8 @@ export {
784
882
  EntityTypeEnum,
785
883
  ExecutionsByTestSuiteArgsSchema,
786
884
  FetchAutomationStatusPayloadSchema,
885
+ FetchIssueDetailsArgsSchema,
886
+ FetchTestSuiteDetailsArgsSchema,
787
887
  ImportAutomationResultsPayloadSchema,
788
888
  IssueExecutionsArgsSchema,
789
889
  IssuesLinkedToTestCaseArgsSchema,
@@ -807,6 +907,7 @@ export {
807
907
  TestCaseListArgsSchema,
808
908
  TestCaseRunsByTestSuiteRunArgsSchema,
809
909
  TestCaseStepsArgsSchema,
910
+ TestCaseStepsWithUdfArgsSchema,
810
911
  TestCaseVersionDetailsArgsSchema,
811
912
  TestCasesByTestSuiteArgsSchema,
812
913
  TestCasesLinkedToRequirementArgsSchema,
@@ -11,8 +11,7 @@ const DEFAULT_FETCH_TESTCASES_PAYLOAD = {
11
11
  isFilterSaveRequired: false
12
12
  };
13
13
  const DEFAULT_CREATE_TESTCASES_PAYLOAD = {
14
- scope: "project",
15
- steps: []
14
+ scope: "project"
16
15
  };
17
16
  const DEFAULT_UPDATE_TESTCASES_PAYLOAD = {};
18
17
  const DEFAULT_FETCH_TESTCASE_DETAILS_PAYLOAD = {
@@ -51,6 +51,16 @@ const FetchCascadeChildValuesArgsSchema = z.object({
51
51
  "Whether to include archived child items in the response (default: false)."
52
52
  )
53
53
  });
54
+ const FetchUdfLayoutArgsSchema = z.object({
55
+ projectKey: CommonFields.projectKeyOptional,
56
+ baseUrl: CommonFields.baseUrl,
57
+ entityType: z.enum(["TC", "TS", "IS"]).describe(
58
+ "Entity type to fetch UDF field definitions for. 'TC' = Test Case (also returns step UDFs in stepFields), 'TS' = Test Suite, 'IS' = Issue."
59
+ ),
60
+ pageName: z.enum(["ADD", "DETAIL"]).optional().default("ADD").describe(
61
+ "'ADD' returns fields for create operations (no fieldID needed). 'DETAIL' returns fields for update operations and includes fieldID (projectUserFieldID) required by the UDF update wrapper. Call with 'DETAIL' before updating an entity's UDF values."
62
+ )
63
+ });
54
64
  const FetchTestRunUdfValuesArgsSchema = z.object({
55
65
  projectKey: CommonFields.projectKeyOptional,
56
66
  baseUrl: CommonFields.baseUrl,
@@ -73,5 +83,6 @@ export {
73
83
  BulkUpdateTestRunUdfsArgsSchema,
74
84
  FetchCascadeChildValuesArgsSchema,
75
85
  FetchTestRunUdfMetadataArgsSchema,
76
- FetchTestRunUdfValuesArgsSchema
86
+ FetchTestRunUdfValuesArgsSchema,
87
+ FetchUdfLayoutArgsSchema
77
88
  };
@@ -21,7 +21,7 @@ class ConnectToSession extends Tool {
21
21
  sessionId: z.string().describe("The ID of the Reflect recording session to connect to")
22
22
  })
23
23
  };
24
- handle = async (args, extra) => {
24
+ handle = async (args, ctx) => {
25
25
  const { sessionId } = args;
26
26
  if (!sessionId) throw new ToolError("sessionId argument is required");
27
27
  if (this.client.isSessionConnected(sessionId)) {
@@ -63,7 +63,7 @@ class ConnectToSession extends Tool {
63
63
  `MCP connect-to-session failed: ${connectError instanceof Error ? connectError.message : String(connectError)}`
64
64
  );
65
65
  }
66
- const mcpSessionId = extra?.sessionId;
66
+ const mcpSessionId = ctx.sessionId;
67
67
  const { platform, test } = connectResponse;
68
68
  this.client.registerConnection(
69
69
  sessionId,
@@ -1,7 +1,8 @@
1
1
  import { appendClientIdentity } from "../../common/info.js";
2
2
  import { ToolError } from "../../common/tools.js";
3
+ import { applyEdits } from "./patch-spec-utils.js";
3
4
  import { buildSubdomainCandidate, buildPortalName, isConflictError, isOrganizationPortalConflict } from "./portal-utils.js";
4
- import { findTableOfContentsItem, buildPortalLiveUrl, normalizeSlug } from "./utils.js";
5
+ import { findTableOfContentsItem, buildPortalLiveUrl, normalizeSlug, isOpenAPI, isAsyncAPI } from "./utils.js";
5
6
  const SWAGGER_URL_REGEX = /\/(apis|domains|templates)\/([^/]+)\/([^/]+)\/([^/]+)/;
6
7
  function hasId(value) {
7
8
  return typeof value === "object" && value !== null && "id" in value;
@@ -841,22 +842,28 @@ class SwaggerAPI {
841
842
  });
842
843
  }
843
844
  /**
844
- * Get API definition from SwaggerHub Registry
845
- * @param params Parameters including owner, api name, version, and options
846
- * @param options Optional transport options
847
- * @returns API definition (OpenAPI/Swagger specification)
845
+ * Execute the shared GET request for an API definition.
848
846
  */
849
- async getApiDefinition(params, options) {
847
+ async fetchApiDefinitionResponse(params, options) {
850
848
  const searchParams = new URLSearchParams();
851
849
  if (params.resolved !== void 0)
852
850
  searchParams.append("resolved", params.resolved.toString());
853
851
  if (params.flatten !== void 0)
854
852
  searchParams.append("flatten", params.flatten.toString());
855
853
  const url = `${this.config.registryBasePath}/apis/${encodeURIComponent(params.owner)}/${encodeURIComponent(params.api)}/${encodeURIComponent(params.version)}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
856
- const response = await fetch(url, {
854
+ return fetch(url, {
857
855
  method: "GET",
858
856
  headers: options?.accept ? { ...this.headers, Accept: options.accept } : this.headers
859
857
  });
858
+ }
859
+ /**
860
+ * Get API definition from SwaggerHub Registry
861
+ * @param params Parameters including owner, api name, version, and options
862
+ * @param options Optional transport options
863
+ * @returns API definition (OpenAPI/Swagger specification)
864
+ */
865
+ async getApiDefinition(params, options) {
866
+ const response = await this.fetchApiDefinitionResponse(params, options);
860
867
  if (!response.ok) {
861
868
  throw new ToolError(
862
869
  `SwaggerHub Registry API getApiDefinition failed - status: ${response.status} ${response.statusText}`
@@ -870,11 +877,22 @@ class SwaggerAPI {
870
877
  }
871
878
  }
872
879
  /**
873
- * Create or Update API in SwaggerHub Registry
874
- * @param params Parameters for creating or updating the API including owner, name, version, specification, and definition
880
+ * Create or Update API in SwaggerHub Registry (tool entry point)
881
+ * @param params Parameters for creating or updating the API including owner, name, and definition
875
882
  * @returns Created or updated API metadata with URL. HTTP 201 indicates creation, HTTP 200 indicates update
876
883
  */
877
884
  async createOrUpdateApi(params) {
885
+ return this.saveApiDefinition(params, { isPrivate: true });
886
+ }
887
+ /**
888
+ * Save an API definition to SwaggerHub Registry
889
+ * @param params Parameters for creating or updating the API including owner, name, and definition
890
+ * @param options Query parameters sent with the save request. `version` targets a
891
+ * specific version; `isPrivate` is only meaningful when creating and is omitted
892
+ * otherwise so an existing API keeps its visibility
893
+ * @returns Created or updated API metadata with URL. HTTP 201 indicates creation, HTTP 200 indicates update
894
+ */
895
+ async saveApiDefinition(params, options = {}) {
878
896
  let contentType;
879
897
  let requestBody;
880
898
  const format = this.detectDefinitionFormat(params.definition);
@@ -893,10 +911,13 @@ class SwaggerAPI {
893
911
  }
894
912
  }
895
913
  const searchParams = new URLSearchParams();
896
- searchParams.append("isPrivate", "true");
914
+ if (options.version) searchParams.append("version", options.version);
915
+ if (typeof options.isPrivate === "boolean")
916
+ searchParams.append("isPrivate", String(options.isPrivate));
917
+ const query = searchParams.toString();
897
918
  const url = `${this.config.registryBasePath}/apis/${encodeURIComponent(
898
919
  params.owner
899
- )}/${encodeURIComponent(params.apiName)}?${searchParams.toString()}`;
920
+ )}/${encodeURIComponent(params.apiName)}${query ? `?${query}` : ""}`;
900
921
  const response = await fetch(url, {
901
922
  method: "POST",
902
923
  headers: {
@@ -908,7 +929,7 @@ class SwaggerAPI {
908
929
  if (!response.ok) {
909
930
  const errorText = await response.text().catch(() => "");
910
931
  throw new ToolError(
911
- `SwaggerHub Registry API createOrUpdateApi failed - status: ${response.status} ${response.statusText}${errorText ? ` - ${errorText}` : ""}. URL: ${url}`
932
+ `SwaggerHub Registry API saveApiDefinition failed - status: ${response.status} ${response.statusText}${errorText ? ` - ${errorText}` : ""}. URL: ${url}`
912
933
  );
913
934
  }
914
935
  const operation = response.status === 201 ? "create" : "update";
@@ -1092,6 +1113,69 @@ class SwaggerAPI {
1092
1113
  }
1093
1114
  return updated;
1094
1115
  }
1116
+ async apiVersionExists({
1117
+ owner,
1118
+ apiName,
1119
+ version
1120
+ }) {
1121
+ const response = await this.fetchApiDefinitionResponse(
1122
+ { owner, api: apiName, version },
1123
+ { accept: "text/plain" }
1124
+ );
1125
+ if (response.status === 404) return false;
1126
+ if (!response.ok) {
1127
+ const errorText = await response.text().catch(() => "");
1128
+ throw new ToolError(
1129
+ `SwaggerHub Registry API apiVersionExists failed - status: ${response.status} ${response.statusText}${errorText ? ` - ${errorText}` : ""}. owner=${owner}, apiName=${apiName}, version=${version}`
1130
+ );
1131
+ }
1132
+ return true;
1133
+ }
1134
+ async patchApi(params) {
1135
+ const createNewVersion = Boolean(params.newVersion);
1136
+ const targetVersion = params.newVersion || params.version;
1137
+ if (createNewVersion) {
1138
+ const exists = await this.apiVersionExists({
1139
+ owner: params.owner,
1140
+ apiName: params.apiName,
1141
+ version: targetVersion
1142
+ });
1143
+ if (exists) {
1144
+ throw new ToolError(
1145
+ `Version ${targetVersion} already exists for ${params.owner}/${params.apiName}. Choose a different version name or omit newVersion to patch in place.`
1146
+ );
1147
+ }
1148
+ }
1149
+ const rawResult = await this.getApiDefinition(
1150
+ { owner: params.owner, api: params.apiName, version: params.version },
1151
+ { accept: "text/plain" }
1152
+ );
1153
+ let text = rawResult;
1154
+ if (!isOpenAPI(text) && !isAsyncAPI(text)) {
1155
+ throw new ToolError(
1156
+ "SwaggerHub Registry API patchApi failed - invalid format. Only OpenAPI and AsyncAPI definitions are supported."
1157
+ );
1158
+ }
1159
+ const { text: patchedText, failed } = applyEdits(text, params.edits);
1160
+ text = patchedText;
1161
+ if (failed.length > 0) {
1162
+ return { failed, saved: false };
1163
+ }
1164
+ const saveResult = await this.saveApiDefinition(
1165
+ {
1166
+ owner: params.owner,
1167
+ apiName: params.apiName,
1168
+ definition: text
1169
+ },
1170
+ createNewVersion ? { version: targetVersion, isPrivate: true } : { version: targetVersion }
1171
+ );
1172
+ return {
1173
+ saved: true,
1174
+ operation: saveResult.operation,
1175
+ version: saveResult.version,
1176
+ url: saveResult.url
1177
+ };
1178
+ }
1095
1179
  }
1096
1180
  export {
1097
1181
  SwaggerAPI
@@ -32,7 +32,13 @@ class FunctionalTestingAPI {
32
32
  let response;
33
33
  try {
34
34
  response = await fetch(`${this.baseUrl}/${relativePath}`, init);
35
- } catch {
35
+ } catch (err) {
36
+ const code = err.cause?.code;
37
+ if (code) {
38
+ throw new ToolError(
39
+ `Failed to reach Swagger Functional Testing API: ${code}. Please verify your settings and network connectivity.`
40
+ );
41
+ }
36
42
  throw new ToolError(
37
43
  "Swagger Functional Testing service is currently unreachable. Retry after a moment."
38
44
  );
@@ -1,4 +1,5 @@
1
1
  import { CreateFunctionalTestingTestResponseSchema, CreateFunctionalTestingTestParamsSchema, RunFunctionalTestingTestParamsSchema, GetFunctionalTestingExecutionTestSchema, ListFunctionalTestingSuiteExecutionsSchema, CancelFunctionalTestingSuiteExecutionSchema, CreateFunctionalTestingSuiteResponseSchema, CreateFunctionalTestingSuiteParamsSchema, RunFunctionalTestingSuiteParamsSchema, GetFunctionalTestingSuiteExecutionSchema, GetFunctionalTestHistoryParamsSchema } from "./functional-testing-types.js";
2
+ import { READ_ONLY, WRITE, WRITE_DESTRUCTIVE } from "./tool-constants.js";
2
3
  const FUNCTIONAL_TESTING_TOOLS = [
3
4
  {
4
5
  title: "List Tests",
@@ -6,17 +7,17 @@ const FUNCTIONAL_TESTING_TOOLS = [
6
7
  summary: "Lists all API tests available in your Swagger Functional Testing account. Use this tool when you need to discover available tests before running them or checking their status. Do not use this tool to retrieve test execution results or history.",
7
8
  handler: "listFunctionalTestingTests",
8
9
  idempotent: true,
9
- readOnly: true
10
+ ...READ_ONLY
10
11
  },
11
12
  {
12
13
  title: "Create Test",
13
14
  toolset: "Functional Testing",
14
- summary: "Creates a new API test in your Swagger Functional Testing workspace. This tool only creates API tests (not browser or native-mobile tests). Use this when you need to programmatically create a test with a defined set of API request steps. Each step requires a URL and may specify an HTTP method (defaults to GET), request body, headers, and redirect handling. Returns the ID and the URL to definition of the newly created test; the ID can be used with `swagger_run_test` to run it, or grouped with other test IDs into a Suite via `swagger_create_suite`.",
15
+ summary: "Creates a new API test in your Swagger Functional Testing workspace. This tool only creates API tests (not browser or native-mobile tests). Use this when you need to programmatically create a test with a defined set of API request steps. Each step requires a URL and may specify an HTTP method (defaults to GET), request body, headers, redirect handling, and assertions: expected HTTP status code ranges, and expected response body assertions (exact match or field-level rules matched by path). Returns the ID and the URL to definition of the newly created test; the ID can be used with `swagger_run_test` to run it or grouped with other test IDs into a Suite via `swagger_create_suite`.",
15
16
  inputSchema: CreateFunctionalTestingTestParamsSchema,
16
17
  outputSchema: CreateFunctionalTestingTestResponseSchema,
17
18
  handler: "createFunctionalTestingTest",
18
- idempotent: false,
19
- readOnly: false
19
+ ...WRITE,
20
+ idempotent: false
20
21
  },
21
22
  {
22
23
  title: "Run Test",
@@ -24,8 +25,9 @@ const FUNCTIONAL_TESTING_TOOLS = [
24
25
  summary: "Runs a specific API test in your Swagger Functional Testing workspace. The execution is asynchronous — it returns an executionId, not the result directly. Use `swagger_get_test_status` with that executionId to track progress and retrieve the final result.",
25
26
  inputSchema: RunFunctionalTestingTestParamsSchema,
26
27
  handler: "runFunctionalTestingTest",
27
- idempotent: false,
28
- readOnly: false
28
+ ...WRITE,
29
+ openWorld: true,
30
+ idempotent: false
29
31
  },
30
32
  {
31
33
  title: "Get Test Status",
@@ -34,7 +36,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
34
36
  inputSchema: GetFunctionalTestingExecutionTestSchema,
35
37
  handler: "getFunctionalTestingExecution",
36
38
  idempotent: true,
37
- readOnly: true
39
+ ...READ_ONLY
38
40
  },
39
41
  {
40
42
  title: "List Suite Executions",
@@ -42,8 +44,8 @@ const FUNCTIONAL_TESTING_TOOLS = [
42
44
  summary: "Lists all executions for a given test suite in your Swagger Functional Testing workspace. Use this tool when you need to review execution history and timings for a specific suite. Do not use this tool to retrieve the status of a single execution or individual test results.",
43
45
  inputSchema: ListFunctionalTestingSuiteExecutionsSchema,
44
46
  handler: "listFunctionalTestingSuiteExecutions",
45
- readOnly: true,
46
- idempotent: true
47
+ idempotent: true,
48
+ ...READ_ONLY
47
49
  },
48
50
  {
49
51
  title: "Cancel Suite Execution",
@@ -51,7 +53,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
51
53
  summary: "Cancels an ongoing test suite execution in your Swagger Functional Testing workspace. Use this tool when you need to stop a long-running or accidentally triggered suite run. Do not use this tool to cancel individual test runs.",
52
54
  inputSchema: CancelFunctionalTestingSuiteExecutionSchema,
53
55
  handler: "cancelFunctionalTestingSuiteExecution",
54
- readOnly: false,
56
+ ...WRITE_DESTRUCTIVE,
55
57
  idempotent: false
56
58
  },
57
59
  {
@@ -61,8 +63,8 @@ const FUNCTIONAL_TESTING_TOOLS = [
61
63
  inputSchema: CreateFunctionalTestingSuiteParamsSchema,
62
64
  outputSchema: CreateFunctionalTestingSuiteResponseSchema,
63
65
  handler: "createFunctionalTestingSuite",
64
- idempotent: false,
65
- readOnly: false
66
+ ...WRITE,
67
+ idempotent: false
66
68
  },
67
69
  {
68
70
  title: "List Suites",
@@ -70,7 +72,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
70
72
  summary: "Lists all test suites available in your Swagger Functional Testing workspace. Use this tool when you need to discover available suites before running them or checking their execution history. Do not use this tool to retrieve individual tests or test suite execution results.",
71
73
  handler: "listFunctionalTestingSuites",
72
74
  idempotent: true,
73
- readOnly: true
75
+ ...READ_ONLY
74
76
  },
75
77
  {
76
78
  title: "Run Suite",
@@ -78,8 +80,9 @@ const FUNCTIONAL_TESTING_TOOLS = [
78
80
  summary: "Runs a specific test suite in your Swagger Functional Testing workspace. The execution is asynchronous — it returns an executionId, not results directly. Use `swagger_get_suite_status` with your suiteId and executionId to track progress and retrieve the final per-test results. Optionally accepts a `tunnelAgentName` argument to override the suite's saved tunnel for this run. Do not use this tool to run a single test — use `swagger_run_test` instead.",
79
81
  inputSchema: RunFunctionalTestingSuiteParamsSchema,
80
82
  handler: "runFunctionalTestingSuite",
81
- idempotent: false,
82
- readOnly: false
83
+ ...WRITE,
84
+ openWorld: true,
85
+ idempotent: false
83
86
  },
84
87
  {
85
88
  title: "Get Suite Status",
@@ -88,7 +91,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
88
91
  inputSchema: GetFunctionalTestingSuiteExecutionSchema,
89
92
  handler: "getFunctionalTestingSuiteExecution",
90
93
  idempotent: true,
91
- readOnly: true
94
+ ...READ_ONLY
92
95
  },
93
96
  {
94
97
  title: "Get Test Execution History",
@@ -97,7 +100,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
97
100
  inputSchema: GetFunctionalTestHistoryParamsSchema,
98
101
  handler: "getFunctionalTestingTestHistory",
99
102
  idempotent: true,
100
- readOnly: true
103
+ ...READ_ONLY
101
104
  }
102
105
  ];
103
106
  export {