Automate cloud connections with the SDKs
Use the JavaScript and Python SDKs to manage connections and inspect hosted discovery. Both are included in the signed discovery bundle. Verify the bundle before using it. Run examples from its extracted root.
These methods call your workspace API. They do not require a collector or local AWS/GCP/Azure SDK. Provider authentication remains in the hosted control plane. Supply a scoped workspace credential from your secret store, never from source control or a public browser application.
Roles and availability
Administrators configure connections, retrieve trust instructions and run access tests. Administrators and analysts can scan verified connections. Viewers can read connections and results. Cancellation remains subject to the operation's ownership and administrator permissions.
Read cloudCapabilities() / cloud_capabilities() first. identityPublished permits trust setup; executionEnabled controls test/scan submission. A published issuer does not establish provider access. Cloud test and scan submission is enabled on qscan.dev; the selected account must grant the documented trust and read permissions.
JavaScript
Save this as an .mjs file. Set QR_TOKEN and QR_CONNECTION_ID for an existing connection.
import {QuantumReady} from './sdk/javascript/index.mjs';
const client = new QuantumReady({
endpoint: process.env.QR_ENDPOINT || 'https://qscan.dev',
token: process.env.QR_TOKEN,
});
const connection = await client.cloudConnection(process.env.QR_CONNECTION_ID);
const capabilities = await client.cloudCapabilities();
if (capabilities.identityPublished) {
const trust = await client.cloudConnectionTrust(connection.id);
console.log('Provider trust subject:', trust.subject);
}
if (capabilities.executionEnabled) {
// Retain this request in your integration's job state before sending.
const request = {
expectedRevision: connection.revision,
requestId: crypto.randomUUID(),
};
const operation = await client.testCloudConnection(connection.id, request);
console.log('Access test reference:', operation.id);
console.log(await client.cloudOperation(operation.id));
} else {
console.log('Hosted tests and scans are not activated.');
}
Submission returns a queued operation, not completed verification. Poll cloudOperation(id) with your own interval and deadline. After completion, fetch the connection again and check its current revision and verification state. Use scanCloudConnection(connection.id, request) with a new retained request ID for an intentional scan of the verified revision.
for await (const result of client.allCloudOperationResults(operationId, {limit: 50})) {
console.log(result);
}
Python
The Python SDK has no third-party dependencies. Set the same environment variables.
import os
import uuid
from sdk.python.quantum_ready import QuantumReady
client = QuantumReady(os.getenv('QR_ENDPOINT', 'https://qscan.dev'), os.environ['QR_TOKEN'])
connection = client.cloud_connection(os.environ['QR_CONNECTION_ID'])
capabilities = client.cloud_capabilities()
if capabilities['identityPublished']:
trust = client.cloud_connection_trust(connection['id'])
print('Provider trust subject:', trust['subject'])
if capabilities['executionEnabled']:
# Retain these values in your integration's job state before sending.
revision = connection['revision']
request_id = str(uuid.uuid4())
operation = client.test_cloud_connection(connection['id'], revision, request_id)
print('Access test reference:', operation['id'])
print(client.cloud_operation(operation['id']))
else:
print('Hosted tests and scans are not activated.')
Use scan_cloud_connection(connection_id, expected_revision, request_id) after successful verification. Inspect results with all_cloud_operation_results(operation_id, limit=50).
Connection lifecycle
Pass the provider configuration described in Cloud connections. Mutations require the revision you reviewed. Updating clears verification and requires another access test.
| Task | JavaScript | Python |
|---|---|---|
| List page | cloudConnections({after, limit}) | cloud_connections(after=None, limit=50) |
| Iterate connections | allCloudConnections({limit}) | all_cloud_connections(limit=50) |
| Read | cloudConnection(id) | cloud_connection(id) |
| Create | createCloudConnection(configuration) | create_cloud_connection(configuration) |
| Update | updateCloudConnection(id, revision, configuration) | update_cloud_connection(id, revision, configuration) |
| Revoke | revokeCloudConnection(id, revision) | revoke_cloud_connection(id, revision) |
| Trust | cloudConnectionTrust(id) | cloud_connection_trust(id) |
| History page | cloudOperations(id, {after, limit}) | cloud_operations(id, after=None, limit=50) |
| Iterate history | allCloudOperations(id, {limit}) | all_cloud_operations(id, limit=50) |
| Status | cloudOperation(operationId) | cloud_operation(operation_id) |
| Result page | cloudOperationResults(operationId, {after, limit}) | cloud_operation_results(operation_id, after=-1, limit=50) |
| Iterate results | allCloudOperationResults(operationId, {limit}) | all_cloud_operation_results(operation_id, limit=50) |
| Cancel | cancelCloudOperation(operationId) | cancel_cloud_operation(operation_id) |
Connection/history cursors are opaque strings. Result cursors are numeric: 0 is valid, and null/None ends pagination. Iterators preserve these distinctions and reject repeated cursors. They paginate existing records; they do not wait for running operations.
Retry, conflicts and partial results
Neither SDK automatically retries mutations. JavaScript test/scan methods require {expectedRevision, requestId}; Python requires both arguments. Generate the ID once and persist it before sending. If submission loses its response, reuse the same ID, revision, connection and action. Inspect history if you cannot recover the request. A fresh ID creates a separate intentional operation.
JavaScript HTTP failures expose error.status and, when supplied, error.retryAfterSeconds. Python JSON requests raise urllib.error.HTTPError with error.code; close the error response after handling it. Respect Retry-After. A 409 revision conflict requires reviewing the current configuration, not automatically overwriting another administrator's change. A 503 execution gate is not a provider permission failure.
Check terminal status (completed, failed, cancelled) and each resource result. Failed or cancelled scans can retain findings accepted earlier. Cancellation prevents further acceptance but does not erase evidence or revoke cloud-side trust. Revoke the provider trust separately when necessary.
Custom agent process identity
Both SDKs support agent heartbeats and the scan lease lifecycle. Use an enrolled agent credential. Generate one process UUID at startup, send it in agentHeartbeat({instanceId, scannerVersion, platform}) / agent_heartbeat(...), and reuse it in each claim. Generate a new claim UUID per attempt; retain that same claim UUID if retrying a lost response. The helpers never retry mutations automatically.
| JavaScript | Python | Purpose |
|---|---|---|
agentHeartbeat(runtime) | agent_heartbeat(runtime) | Report process and runtime metadata |
claimJob(claimId, instanceId) | claim_job(claim_id, instance_id) | Claim an assigned scan with stable process identity |
renewJob(jobId, leaseToken) | renew_job(job_id, lease_token) | Keep an active lease current |
completeJob(jobId, result) | complete_job(job_id, result) | Report completed or failed work with the current lease token |
The completion result contains leaseToken, status, and the accepted observations count. Discovery must enforce the local allowlist, maintain the lease, and stop work when ownership is lost. These helpers are transport methods, not a complete agent loop; use the provided scanner for the full implementation. Report the real runtime distribution and version. Claim identity is correlated evidence, not binary attestation.
Retire and archive a connection
Revoke first, then archive using the returned revision. The operations preserve evidence and history. Restore changes list visibility only; it never restores trust or scan access.
const revoked = await client.revokeCloudConnection(connection.id, connection.revision);
const archived = await client.archiveCloudConnection(revoked.id, revoked.revision);
for await (const item of client.allCloudConnections({archived: true})) {
console.log(item.id, item.state);
}
// When intentionally restoring visibility:
await client.unarchiveCloudConnection(archived.id, archived.revision);
Python equivalents are archive_cloud_connection(id, expected_revision), unarchive_cloud_connection(id, expected_revision) and all_cloud_connections(archived=True). Ordinary connection lists exclude archived entries. Direct reads and operation history remain available. Retrying the latest archive/restore action with its original revision is idempotent; a stale revision after subsequent changes requires rereading the record.
Retained resource context
New per-resource outcomes include resource (the exact configured identifier),
provider, connectionRevision and checkedAt. These values are recorded when the
resource outcome is accepted. They remain unchanged if the connection is subsequently
edited, revoked or archived. Failed outcomes also retain this context; access tests
still do not store provider metadata observations.
JavaScript, Python and the OAuth MCP cloud_operation_results tool return these
fields with each result. They are optional for legacy records. Do not infer a missing
identifier by indexing the current connection scope unless its revision equals the
operation's connectionRevision. Follow every result page to assess full coverage.
Recurring scans
Read the connection and schedule immediately before authorizing. This example delegates recurring scanning to the current administrator credential; its expiry or revocation ends that authority. Use a managed credential with an appropriate lifetime and rotate through explicit reauthorization. The SDK does not extend credentials.
const connection = await client.cloudConnection(process.env.QR_CONNECTION_ID);
const {schedule} = await client.cloudSchedule(connection.id);
await client.manageCloudSchedule(connection.id, {
operation: 'save',
expectedRevision: schedule?.revision || 0,
expectedConnectionRevision: connection.revision,
intervalSeconds: 86400,
confirmDelegation: true,
});
Python exposes cloud_schedule(connection_id) and manage_cloud_schedule(connection_id, configuration) with the same request fields. To pause or remove, send operation: 'pause' or 'remove' and the current expectedRevision. Read again after an uncertain response; do not replay a save blindly. Changes invalidate active scheduled work at its next authorization check. Only verified connections can be scheduled, intervals are one hour to 30 days, and overlapping work is skipped. See recurring scan behavior.
OAuth MCP clients can read cloud_schedule and request cloud_schedule_manage. Saving requires explicit administrator delegation; a tool must not infer that approval from a request to run a single scan.
Permanently delete a revoked connection
Deletion requires administrator access and explicit confirmation. Read the current revision before starting, then retain that revision for retries after an uncertain response.
const current = await client.cloudConnection(connection.id);
const result = await client.deleteCloudConnection(current.id, current.revision, true);
if (result.deleted !== true) throw new Error('Deletion was not confirmed');
current = client.cloud_connection(connection_id)
result = client.delete_cloud_connection(current['id'], current['revision'], True)
assert result['deleted'] is True
The connection must already be revoked; an archived revoked connection can also be deleted. The API is POST /api/v1/cloud-connections/{id}/delete with expectedRevision and confirm: true. The MCP tool is cloud_connection_delete, with the same fields plus id.
Settings and schedules are removed, unfinished operations are cancelled, and in-flight results cannot publish after deletion. Existing findings, audit and operation results remain; cloudOperations(id) / cloud_operations(id) still enumerate retained history. Provider-side trust and already-issued token validity are unchanged. A minimal deletion receipt supports same-revision retries and prevents reuse of the original creation request ID.