Docs API automation in CI/CD

Automate Mockarty in CI/CD

Use these examples when a pipeline needs to prepare mocks or run checks. Replace sample server addresses, target URLs, and token values with your own. For endpoint details, see the API Reference.

These CI examples use an API token with permission for the workspace you are testing. Set it in MOCKARTY_API_KEY before running the cURL commands; they also use jq to read JSON responses. For SDK client setup, see the SDK Guide.

A new automation opens at the top of the form, starting with its name.

The list shows your automations that your current workspace permissions allow you to read. Managing or running an automation requires write permission for its action. Deleting an automation stops future runs; its recorded run history remains available with the corresponding read permission.

On a self-hosted server with Agent work enabled, the Action list offers Start a mission when your workspace permissions allow it. Each firing starts one autonomous mission. See Autonomous Missions for the goal, autonomy and run history. Without that entitlement, you can read or disable retained mission automations but cannot create, change or enable them.

When a native Desktop instruction is scheduled once, it keeps its original scheduled time while an earlier run of the same automation is active. It can start after that run clears, within ten minutes of its own scheduled time and before its end date. If that window closes first, its history records the original time and the reason. If Run now and the scheduled time coincide exactly, the scheduled occurrence has priority. For other automations, a run due during a previous active run is skipped and recorded in history.

Read GET /api/v1/namespaces/{namespace}/automations/{id} to see a Desktop automation’s current activeFire. A prepared occurrence is waiting to dispatch. Its waitReason, when present, reports what blocked the most recent attempt. A dispatched instruction is waiting for confirmation of delivery. Use its id in the newest-first history at GET /api/v1/namespaces/{namespace}/automations/{id}/fires to find the final outcome. A scheduled overlap has its own history row and scheduled time. It can still be read after the earlier active run finishes and the summary’s lastOutcome changes.

For a native instruction, dispatchDeadlineAt shows the last time it can dispatch under its original schedule. The ten-minute window starts at that occurrence’s dueAt; an earlier end date or a later pause can stop it sooner. Runner load fields such as queueDepth describe target selection when it occurs. activeFire shows the single live occurrence for this automation.

Harness reminders and instructions

The API and MCP accept a JSON object in payload. For a session reminder, it contains session and text.

In a local Desktop Harness session, open Settings (gear) → Automations. Choose Reminder or Session instruction, enter any task or reminder, choose a date and time or a repeat, and save. The same controls are available when opening that Desktop in a browser. The reminder appears in the conversation with its scheduled time; it does not ask a model to answer and does not require a test collection.

You can edit, pause or delete a reminder, run it now, and view its run history. It stays attached to its original session and local profile. If the application was closed, the original Desktop records one overdue reminder after reopening; a repeating reminder then continues with its next future time. An inactive profile waits until you select it again. Deleted profiles and revoked access do not redirect reminders to another session.

Each explicit Run now after the previous reminder finishes records a new reminder. If a reply is lost, check the run history before trying again.

For API or MCP clients, read GET /api/v1/namespaces/{namespace}/automations first. Its kinds[].fireAdmitted describes current runtime availability. session_reminder accepts payload: {"session":{"kind":"native","id":"<session-id>"},"text":"<reminder>"} and exactly one of runAt (an ISO timestamp with offset) or cronExpression. The application resolves the device and profile; do not supply credentials or execution identity. A native MCP session can obtain its current session reference from current_namespace.harnessSession. Creating through MCP requires Full access and the current workspace permissions.

Creation is not idempotent. If a response is lost, inspect your list before retrying. Updates use the existing updatedAt as revision. Use session_prompt with the same session/text payload to send an instruction to that conversation. It uses the session’s model and access settings. Its text is labelled as an automation in the chat. A completed run means the instruction was accepted. Follow the chat for the result. A busy session waits, subject to the ten-minute pending-run limit. After an uncertain delivery, the application checks the recorded result and never automatically resends the same instruction. Keep Desktop running with the original local profile selected. Use new_session_prompt with payload { "projectId": "registered-project-id", "text": "Review changes and summarize risks" } for a separate conversation. Each occurrence creates one conversation in the registered local project and sends its instruction. The current default model profile is used (or the only enabled profile). In Automations, choose Schedule a Harness task, project, instruction and time. An uncertain creation result is shown without automatically creating another conversation.

From the Automations catalogue, Start a new project session opens by default when a project and model are available. You can also open Settings (gear) → Automations from the Harness start screen before sending a message. Choose a project and an instruction. Each scheduled occurrence starts a fresh conversation even when there are no previous chats.

To schedule a session action, use the original Local profile in Desktop. A server or a mirrored session cannot accept that schedule. If the target Desktop or profile is unavailable, creating or updating the schedule returns 409 session_target_unavailable. An active occurrence instead returns 409 live_occurrence. Check the catalogue again before retrying.

Scheduled collection runs

In the console’s Automations editor, expand Collections and tick the API collections to run. The list includes collections shared with you in the current Space. If the list is empty, create one in API Tester before saving a new run. If the list fails to load, reopen the editor to retry. Editing another field preserves saved collections the picker could not list. Untick a listed collection to remove it.

For a fixed target, choose a registered runner with the API-test capability. A runner that polls the server can accept a scheduled collection run. The server checks the target against your current Space and runner access. Open the automation’s run history to see the selected target and outcome.

In the mobile web app, choose a ready-made recurring schedule or enter a custom cron expression. For a fixed runner, choose it from the server list before saving. If a list fails to load while editing, the form keeps saved collections, the environment, and the runner. Reopen the editor to reload the list.

Choose New automation to open the editor. Close the editor or run-history dialog with its close button, Escape, or a click outside the dialog. Closing the editor before saving discards the draft. If you close it after pressing Save, the server may still finish that request.

For a Test run, open Collections in the same row as Action and select the collections to run. You can collapse the list without changing the selection.

Once a run has been prepared, later edits apply to future runs. Disabling the automation or moving its end date into the past prevents an occurrence that has yet to be queued. A task already sent to the runner queue can still run. Runs waiting longer than ten minutes expire instead of starting unexpectedly late. If the pending-run limit is reached, Run now returns 429 (backlog_full); wait for pending runs to finish before trying again.

Examples

Running API Tests from CI

cURL

TOKEN="${MOCKARTY_API_KEY:?Set MOCKARTY_API_KEY first}"
BASE="${MOCKARTY_URL:-http://127.0.0.1:5770}/api/v1"

# 1. Create a collection
COLLECTION_ID=$(curl -s -X POST "$BASE/api-tester/collections" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "CI Tests", "description": "Automated test suite"}' | jq -r '.id')

# 2. Add a request with test script
curl -X POST "$BASE/api-tester/collections/$COLLECTION_ID/requests" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Get Users",
    "requestData": {"method": "GET", "url": "http://127.0.0.1:5770/stubs/sandbox/api/users"},
    "testScript": "mk.test(\"Status is 200\", function() { mk.response.to.have.status(200); });"
  }'

# 3. Execute the collection (runs all requests + test scripts)
RUN_ID=$(curl -s -X POST "$BASE/api-tester/collections/$COLLECTION_ID/execute" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{}' | jq -r '.testRunId')

# 4. Poll for results
curl -s "$BASE/api-tester/test-runs/$RUN_ID" \
  -H "X-API-Key: $TOKEN" | jq '.status, .summary'

CLI

# Run a collection stored in Mockarty, by name
mockarty-cli run collection "CI Tests"

# Or a collection file, exporting a JUnit report for CI
mockarty-cli run -f ci-tests.json --reporter junit:results.xml

Go

// Create a collection and execute it
col, err := client.Collections().Create(context.Background(), &mockarty.Collection{
    Name:        "CI Tests",
    Description: "Automated test suite",
})

// Execute the collection
run, err := client.Collections().Execute(context.Background(), col.ID)
fmt.Printf("Run ID: %s, Status: %s\n", run.ID, run.Status)

Python

# Create a collection and execute it
col = client.collections.create({
    "name": "CI Tests",
    "description": "Automated test suite",
})

# Execute the collection
run = client.collections.execute(col.id)
print(f"Run ID: {run.id}, Status: {run.status}")

Java

// Create a collection and execute it
Map<String, Object> col = client.collections().create(Map.of(
    "name", "CI Tests",
    "description", "Automated test suite"
));

String collectionId = (String) col.get("id");
Map<String, Object> run = client.collections().execute(collectionId);
System.out.println("Run ID: " + run.get("testRunId"));

Running Performance Tests from CI

The cURL and SDK examples submit a test to Mockarty, so connect a runner first. The CLI examples run locally unless you select server execution. Replace the script’s stub URL if your Mockarty server is not local.

cURL

TOKEN="${MOCKARTY_API_KEY:?Set MOCKARTY_API_KEY first}"
BASE="${MOCKARTY_URL:-http://127.0.0.1:5770}/api/v1"

# Run a performance test with an inline script
curl -X POST "$BASE/perf/run" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "script": "import http from \"k6/http\"; export default function() { http.get(\"http://localhost:5770/stubs/sandbox/api/users\"); }",
    "options": {"vus": 10, "duration": "30s"}
  }'

# Check results
curl -s "$BASE/perf-results" -H "X-API-Key: $TOKEN" | jq '.[0]'

CLI

# Run a performance test from a saved perf-config file
mockarty-cli perf run --from-config load-test.json

# Run a script with inline load options
mockarty-cli perf run ./load-test.js --vus 10 --duration 30s

Go

// Run a performance test
task, err := client.Perf().Run(context.Background(), &mockarty.PerfConfig{
    Script:  `import http from "k6/http"; export default function() { http.get("http://localhost:5770/stubs/sandbox/api/users"); }`,
    Options: &mockarty.PerfOptions{VUs: 10, Duration: "30s"},
})
fmt.Println("Task ID:", task.ID)

// List results
results, err := client.Perf().ListResults(context.Background())

Python

# Run a performance test
result = client.perf.run({
    "script": 'import http from "k6/http"; export default function() { http.get("http://localhost:5770/stubs/sandbox/api/users"); }',
    "options": {"vus": 10, "duration": "30s"},
})

# List results
results = client.perf.list_results()

Java

// Run a performance test
Map<String, Object> result = client.perf().run(Map.of(
    "script", "import http from \"k6/http\"; export default function() { http.get(\"http://localhost:5770/stubs/sandbox/api/users\"); }",
    "options", Map.of("vus", 10, "duration", "30s")
));

Running Fuzzing from CI

Replace https://api.example.com with an API you are allowed to test. The cURL and SDK examples need a connected runner; the CLI example runs locally.

cURL

TOKEN="${MOCKARTY_API_KEY:?Set MOCKARTY_API_KEY first}"
BASE="${MOCKARTY_URL:-http://127.0.0.1:5770}/api/v1"

# 1. Create fuzz config
CONFIG_ID=$(curl -s -X POST "$BASE/fuzzing/configs" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "API Fuzz",
    "targetBaseUrl": "https://api.example.com",
    "sourceType": "manual",
    "strategy": "security",
    "seedRequests": [{"id": "seed-1", "method": "POST", "url": "/api/users"}],
    "payloadCategories": ["sqli", "xss"],
    "options": {"maxRequests": 100, "concurrency": 2}
  }' | jq -r '.id')

# 2. Start fuzz run
RUN_ID=$(curl -s -X POST "$BASE/fuzzing/run" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"configId": "'$CONFIG_ID'"}' | jq -r '.resultId')

# 3. Check findings for this run
curl -s "$BASE/fuzzing/findings?runId=$RUN_ID" \
  -H "X-API-Key: $TOKEN" | jq '.findings'

CLI

# Fuzz an API described by an OpenAPI spec
mockarty-cli fuzz --target http://target:8080 \
  --spec openapi.yaml \
  --categories sqli,xss \
  --duration 1m

Go

// Create a fuzz config and run it
config, err := client.Fuzzing().CreateConfig(context.Background(), &mockarty.FuzzingConfig{
    Name:              "API Fuzz",
    TargetBaseURL:     "https://api.example.com",
    SourceType:        "manual",
    Strategy:          "security",
    SeedRequests:      []map[string]any{{"id": "seed-1", "method": "POST", "url": "/api/users"}},
    PayloadCategories: []string{"sqli", "xss"},
    Options:           map[string]any{"maxRequests": 100, "concurrency": 2},
})

run, err := client.Fuzzing().StartFromConfig(context.Background(), config.ID)

// Check findings
findings, err := client.Fuzzing().ListFindings(context.Background())
for _, finding := range findings {
    if finding.RunID == run.ID { fmt.Println(finding.Title) }
}

Python

# Create a fuzz config and run it
config = client.fuzzing.create_config({
    "name": "API Fuzz",
    "targetBaseUrl": "https://api.example.com",
    "sourceType": "manual",
    "strategy": "security",
    "seedRequests": [{"id": "seed-1", "method": "POST", "url": "/api/users"}],
    "payloadCategories": ["sqli", "xss"],
    "options": {"maxRequests": 100, "concurrency": 2},
})

run = client.fuzzing.start_from_config(config.id)

# Check findings
findings = [f for f in client.fuzzing.list_findings() if f.get("runId") == run.id]

Java

// Create the config with the cURL example above, then use its returned ID.
String configId = "<config-id>";
FuzzingRun run = client.fuzzing().startFromConfig(configId);
List<FuzzingFinding> findings = client.fuzzing().listFindings().stream()
    .filter(f -> run.getId().equals(f.getRunId()))
    .toList();

Importing OpenAPI/Postman/HAR

cURL

TOKEN="${MOCKARTY_API_KEY:?Set MOCKARTY_API_KEY first}"
BASE="${MOCKARTY_URL:-http://127.0.0.1:5770}/api/v1"

# Send the OpenAPI file as JSON content and generate mocks in sandbox
jq -Rs --arg ns sandbox '{content: ., namespace: $ns}' < openapi.yaml | curl -X POST "$BASE/generators/openapi" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  --data-binary @-

# Import Postman collection to API Tester
# (the exported file's JSON goes under the collectionJson key)
curl -X POST "$BASE/api-tester/import/postman" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"collectionJson\": $(cat collection.json)}"

# Import Postman environment (*.postman_environment.json);
# activate=true makes it your active environment right away
curl -X POST "$BASE/api-tester/import/postman-env" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"environmentJson\": $(cat staging.postman_environment.json), \"activate\": true}"

# Import HAR recording (file content under the content key)
curl -X POST "$BASE/api-tester/import/har" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"content\": $(jq -Rs . < recording.har)}"

# Import WSDL for SOAP testing — from a URL or inline content
curl -X POST "$BASE/api-tester/import/wsdl" \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/service?wsdl"}'

CLI

# Generate mocks from an OpenAPI spec (namespace defaults to "sandbox")
mockarty-cli --namespace sandbox generate openapi openapi.yaml --upload

# Convert a Postman collection into mock files
mockarty-cli generate postman collection.json

# Generate mocks from a HAR recording
mockarty-cli generate har recording.har

Go

// Generate mocks from an OpenAPI/Swagger spec
spec, _ := os.ReadFile("openapi.yaml")
result, err := client.Generator().FromOpenAPI(context.Background(), &mockarty.GeneratorRequest{
    Spec:      string(spec),
    Namespace: "sandbox", // optional, "sandbox" is the default
})

// Import a Postman collection
data, _ := os.ReadFile("collection.json")
importResult, err := client.Import().Postman(context.Background(), data)

Python

# Generate mocks from an OpenAPI/Swagger spec
result = client.generator.from_openapi({
    "content": open("openapi.yaml").read(),
    "namespace": "sandbox",  # optional, "sandbox" is the default
})

# Import a Postman collection
import json
import_result = client.imports.postman(json.load(open("collection.json")))

Java

// Generate mocks from an OpenAPI/Swagger spec
GeneratorResponse result = client.generator().fromOpenAPI(
    new GeneratorRequest()
        .spec(Files.readString(Path.of("openapi.yaml")))
        .namespace("sandbox"));

// Import a Postman collection
ImportResult importResult = client.imports().postman(
    Files.readString(Path.of("collection.json")), "sandbox");

Setting Up Mocks Before Tests

cURL

# Create a mock for the sandbox workspace
TOKEN="${MOCKARTY_API_KEY:?Set MOCKARTY_API_KEY first}"
curl -X POST http://localhost:5770/api/v1/mocks \
  -H "X-API-Key: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "ci-user-service",
    "namespace": "sandbox",
    "http": {"route": "/api/users/list", "httpMethod": "GET"},
    "response": {
      "statusCode": 200,
      "payload": {"id": "$.fake.UUID", "name": "Test User"}
    }
  }'

# Verify mock is active
curl http://localhost:5770/stubs/sandbox/api/users/list
# Returns: {"id": "a1b2c3d4-...", "name": "Test User"}

# Cleanup after tests
curl -X DELETE -H "X-API-Key: $TOKEN" \
  http://localhost:5770/api/v1/mocks/ci-user-service

CLI

# Create a mock from a JSON file
mockarty-cli mock create --file ci-mocks.json

# Verify mock is active
curl http://localhost:5770/stubs/sandbox/api/users/list

# Cleanup after tests
mockarty-cli mock delete ci-user-service

Go

// Create mock for CI
mock := mockarty.NewMockBuilder().
    ID("ci-user-service").
    Namespace("sandbox").
    HTTP(func(h *mockarty.HTTPBuilder) {
        h.Route("/api/users/list").Method("GET")
    }).
    Response(func(r *mockarty.ResponseBuilder) {
        r.Status(200).JSONBody(map[string]any{
            "id":   "$.fake.UUID",
            "name": "Test User",
        })
    }).
    Build()

_, err := client.Mocks().Create(context.Background(), mock)

// ... run tests ...

// Cleanup
err = client.Mocks().Delete(context.Background(), "ci-user-service")

Python

# Create mock for CI
mock = (
    MockBuilder.http("/api/users/list", "GET")
    .id("ci-user-service")
    .namespace("sandbox")
    .respond(200, body={"id": "$.fake.UUID", "name": "Test User"})
    .build()
)
client.mocks.create(mock)

# ... run tests ...

# Cleanup
client.mocks.delete("ci-user-service")

Java

// Create mock for CI
Mock mock = MockBuilder.http("/api/users/list", "GET")
    .id("ci-user-service")
    .namespace("sandbox")
    .respond(200, Map.of("id", "$.fake.UUID", "name", "Test User"))
    .build();

client.mocks().create(mock);

// ... run tests ...

// Cleanup
client.mocks().delete("ci-user-service");

Goals in a native Harness conversation

A goal is explicit ongoing work in one conversation. It is separate from a TODO
list or a timed automation. Ask to set a goal only when you want Harness to keep
working toward that objective. Current access rules still apply: a research goal
can use Read-only, while edits and other actions retain their normal restrictions.

The namespace API provides:

  • GET /api/v1/namespaces/{namespace}/harness-goals?sessionId={nativeSessionId}:
    {goals, available, reason?}, including completed goals. Reading starts no work.
  • POST /api/v1/namespaces/{namespace}/harness-goals: create an explicit goal.
  • GET /api/v1/namespaces/{namespace}/harness-goals/{id}: read {goal}.
  • POST /api/v1/namespaces/{namespace}/harness-goals/{id}/control: send
    {revision, action, note?} with pause, resume, stop, archive or complete.

Create takes an operationId UUID, session: {kind: "native", id}, goal, optional
acceptanceCriteria, and optional positive budgetTokens and maxTurns. Obtain
the conversation ID from Harness or the MCP current_namespace result. Keep the
same operation ID when checking an uncertain create; changing it can represent
another request. Create and control return {goal}. A second active goal in the
same conversation returns 409 with activeId.

The goal strip shows active elapsed time, excluding pauses. Removing a goal archives it
and prevents future automatic turns while preserving the conversation and its receipts.

Pause and stop prevent subsequent continuations. They do not retract an instruction
already accepted by the model; use the conversation’s stop control for its current
answer. Manual instructions and pending decisions take priority. Continuation uses
the same local profile and conversation after a restart. It waits when that profile
is not current. If delivery cannot be confirmed, Harness does not resend it
blindly. A confirmed interrupted step can be continued explicitly as a new step
when the conversation is ready. An uncertain step cannot be resumed; its control
request returns 409. Check the goal’s reason and history before requesting new work.

User completion is marked user_confirmed. A model’s completion assessment is
marked agent_report; neither label claims that every criterion was independently
machine-verified. The model uses harness_goal_report for the exact current goal
turn; ordinary prose or completing TODOs does not complete a goal. This narrowly
scoped report is also available in Edit and Read-only and grants no additional
execution access. General MCP changes still require Full.

Limits are optional. Harness checks the token limit between confirmed goal turns.
It adds the measured input and output of those turns. If the engine cannot confirm
complete usage, for example for delegated work with unconfirmed usage,
spentTokens is null and usageKnown is false. A goal with a token limit
pauses in that case. Harness also pauses at an internal continuation safety limit; an
explicit resume can authorize another bounded period. This safety limit is not
shown as a budget chosen by the user.

The current goal workflow is for native local conversations on the active Desktop
host, including its browser interface. It does not claim remote-host goal execution.
MCP offers harness_goals_list, harness_goal_set, harness_goal_get, and
harness_goal_control; creation requires an explicit user request. These interactive
conversation controls are not added to the SDKs or CLI as generic REST wrappers.