πŸ” Introduction

  • iframe is a standard protocol for embedding one website into another.
  • Iframes are particularly useful for enabling third-party agents with existing web applications to seamlessly onboard onto the MuleRun platform.
  • MuleRun supports Iframe Agents as one of its primary agent integration methods, allowing external developers to host and manage their agent logic independently while being securely embedded within MuleRun.

πŸ—οΈ System Architecture

image

Component Summary

ComponentDescription
Agent Configuration ParamsThe param details when you create an Iframe agent from Creator Studio iframe agent template
Iframe URL ProtocolThe URL(s) that MuleRun opens when a user starts or resumes a session. Parameters are passed via query string for authentication and context. Separate URLs can be configured for starting and sharing sessions.
Metering APIA MuleRun platform API that allows agent creators to report usage costs for a given session. Enables fine-grained billing based on resource consumption.
Metering Get Reports APIA MuleRun platform API that allows agent creators to get the usage costs for a given session and its current session status.

πŸ“ˆ Agent Configuration Params

Configuration ParamUsageDefault
Start Session UrlThe Iframe url that starts a new session on creator’s website
Share Session UrlThe Iframe url that starts a new shared session(playback) on creator’s website
Agent KeyThe key used for generating signature AND calling metering api, this key should not be expose to any 3rd party
Max AgeThe maximum age of the session, in minutes2880
Start Session Refresh IntervalThe time interval between every two re-generations of start session full url(in minutes). when set to 0, it means the start session url will be created only once.0

πŸ”Œ Iframe URL Protocol

Behavior Overview

  • When a new session starts, MuleRun redirects the user to the Start Session URL, including all required parameters.
  • On page refresh or re-entry into the session, the Start Session URL is loaded again with updated parameters.
  • When a session ends (either terminated or time out), a Share Session URL may be triggered. The user may choose to view or share the session playback.
  • When a visitor accesses the shared playback of a session, the Share Session URL is opened.

URL Schema Design

https://{start-session-url}?
  userId={user_id}&
  sessionId={session_id}&
  agentId={agent_id}&
  time={unix_timestamp}&
  signature={hmac_signature}&
  origin={platform_origin}&
  nonce={nonce}
Note: All parameters are URL-encoded during transmission. During signature verification, they must be URL-decoded, parsed into a dictionary, sorted, and serialized as JSON before HMAC calculation.

Routing Example

Your agent’s endpoint: https://third-party-url.com/session/

Parameter Definitions

ParameterTypeExample
userIdstring (64 chars)3e5215afce4ef92284c336110cc6dd3d0107971687396cbb3dbbbc625bc3807d
sessionIdstring (36 chars, UUID)7469a916-d0c6-4161-bd33-1ebac5c834c4
agentIdstring (36 chars, UUID)924751e0-196e-4b22-bdbd-f0a9ac6a4e39
time (UTC)string (integer timestamp)1755667994
originstringmulerun.com
noncestring (36 chars, UUID)bd3ff1f9-d5f3-4019-848a-7c74bba0b73a
signaturestring (64 chars, SHA-256 HMAC hex)2ae8a94f29beda81f59beca248824fcd91484c5f5744432a47ce2cea0a5c9a6f

Example URL

https://third-party-url.com/session?
  userId=377860de68ec786a091beb5d62836797bac4cf98074bd74af56bcec863696146&
  sessionId=25404aaa-b407-4da7-9eb5-8ea6cbcfc9ee&
  agentId=924751e0-196e-4b22-bdbd-f0a9ac6a4e39&
  time=1755671232&
  origin=mulerun.com&
  nonce=bd3ff1f9-d5f3-4019-848a-7c74bba0b73a&
  signature=dd4f2b82b054ce4324175c83ea9219772caa08863ba76e47cc7f03c57a65ce76

Signature Generation (Python Example)

import json
from datetime import datetime, timezone
import hmac
from hashlib import sha256

nonce = "bd3ff1f9-d5f3-4019-848a-7c74bba0b73a"
request_params = {
    "userId": user_sha_id,
    "sessionId": str(session_id),
    "agentId": "924751e0-196e-4b22-bdbd-f0a9ac6a4e39",
    "time": str(int(datetime.now(timezone.utc).timestamp())),
    "origin": "mulerun.com",
    "nonce": nonce,
}

# Ensure parameters are sorted by key before serialization
sorted_json = json.dumps(request_params, separators=(',', ':'), sort_keys=True)
signature = hmac.new(agent_key.encode(), json.dumps(request_param, sort_keys=True, separators=(',', ':')).encode(), sha256).hexdigest()

request_params["signature"] = signature

βœ… Important: Use json.dumps(..., sort_keys=True) to ensure consistent serialization order.

Signature Verification (Python Example)

from urllib.parse import parse_qs
import hmac
from hashlib import sha256
import json

agent_key = "your-agent-key"  # Shared secret between MuleRun and Agent
query_string = "userId=...&signature=..."

# Parse query string
query_dict = {k: v[0] if len(v) == 1 else v for k, v in parse_qs(query_string).items()}
received_signature = query_dict.pop("signature")

# Recreate canonical string for HMAC
sorted_payload = json.dumps(query_dict, separators=(',', ':'), sort_keys=True)
calculated_hmac = hmac.new(
    agent_key.encode(),
    sorted_payload.encode(),
    sha256
).hexdigest()

# Secure comparison
if hmac.compare_digest(calculated_hmac, received_signature):
    # Valid request
    pass
else:
    # Invalid or tampered request
    raise Exception("Invalid signature")

πŸ” The agent_key is your Agent specific key that you can copy from your agent info in Creator Studio. It should be not be exposed to any 3rd party.

πŸ”’ Security Considerations

To ensure secure and trusted communication, the following mechanisms are implemented:
MechanismPurpose
User ID HashingRaw user identifiers are hashed (e.g., SHA-256) to protect user privacy.
HMAC SignaturePrevents tampering of query parameters. Ensures authenticity of the request.
Timestamp ValidationRequests must be within a valid time window (e.g., Β±5 minutes) to prevent replay attacks.
Origin Domain WhitelistingOnly specified domains are allowed to receive iframe requests. Prevents unauthorized embedding.
Nonce UsageUnique per-request identifier to prevent replay attacks and ensure freshness.
βœ… Recommended Validation Logic:

πŸ“Š Metering Report API

Used by agents to report usage and enable accurate billing.

Endpoint

POST https://mulerun.com/v1/metering/report
This is a temporary endpoint that will be moved to https://api.mulerun.com/sessions/metering/report in October 2025

Headers

HeaderTypeRequiredDescription
AuthorizationstringYesBearer token: Authorization: Bearer <your_agent_key_here>
Content-TypestringYesMust be application/json

Request Body

{
  "agentId": "123e4567-e89b-12d3-a456-426614174000",
  "sessionId": "987e6543-e21b-45cd-b678-123456789abc",
  "cost": 1050,
  "timestamp": "2023-10-27T10:00:00Z",
  "isFinal": false,
  "meteringId": "abc123efg-456h-789i-jklm-123nop456qr"
}

Field Descriptions

FieldTypeRequiredDescription
agentIdstring (UUID)YesUnique ID assigned by MuleRun to identify the agent.
sessionIdstring (UUID)YesIdentifier for the current user session. Multiple reports with the same sessionId belong to the same session.
costintegerYesUsage cost in units of 0.0001 credits. For example, 1050 = 0.105 credits. Must be positive.
timestampstring (ISO 8601 UTC)YesUTC timestamp indicating when this usage was recorded.
isFinalbooleanNoIf true, marks this as the final report for the session(AND session will be terminated). Defaults to false.
meteringIdstring (UUID v4 recommended)YesA globally unique idempotency key. Prevents duplicate processing of the same report.

βœ… Idempotency Mechanism

  • New meteringId: The request is processed and stored. A success response is returned.
  • Duplicate meteringId: The system returns the cached response without reprocessing.
  • This ensures safe retries without double billing.

πŸ“œ Additional Billing & Session Rules

1. Timestamp Ordering

  • All metering reports must have monotonically increasing timestamp values.
  • Out-of-order reports may be rejected or handled with warnings during auditing.

2. Final State Idempotency

  • Once a report with "isFinal": true is accepted for a sessionId, the session is marked as completed.
  • Any further reports for the same sessionId will be ignored (cached response returned).

3. Session Termination Handling

  • No Reports Received: If no metering reports are sent, MuleRun will charge based on internal resource tracking.
  • Grace Period: If no final report is received before session end, late reports are accepted within 1 minute after termination.
  • Abnormal Termination: In cases of crash or forced termination, the grace period does not apply β€” charges are settled immediately.

4. Negative Credit Balance

  • If a user’s credit balance becomes negative, the session is immediately terminated.
  • All subsequent metering reports for that session will be ignored.

βœ… Success Response

{
  "status": "success",
  "meteringId": "abc123efg-456h-789i-jklm-123nop456qr"
}

FieldTypeDescription
statusstring"success" indicates the report was accepted.
meteringIdstringThe idempotency key stored by MuleRun for this record.

❌ Error Responses

400 Bad Request

{
  "error": {
    "type": "invalid_request_error",
    "message": "Parameter 'cost' must be a positive number."
  }
}

401 Unauthorized

{
  "error": {
    "type": "authentication_error",
    "message": "Invalid or missing authentication token."
  }
}

429 Too Many Requests

{
  "error": {
    "type": "rate_limit_error",
    "message": "You have exceeded the rate limit."
  }
}

500 Internal Server Error

{
  "error": {
    "type": "api_error",
    "message": "An internal error occurred. Please try again."
  }
}


πŸ’‘ Example cURL Request

curl -X POST "https://api.mulerun.com/v1/metering/report" \
  -H "Authorization: Bearer <your_agent_key_here>" \
  -H "Content-Type: application/json" \
  -d '{
    "agentId": "123e4567-e89b-12d3-a456-426614174000",
    "sessionId": "987e6543-e21b-45cd-b678-123456789abc",
    "cost": 1050,
    "timestamp": "2023-10-27T10:00:00Z",
    "isFinal": false,
    "meteringId": "abc123efg-456h-789i-jklm-123nop456qr"
  }'

πŸ› οΈ Best Practice: Generate a new UUIDv4 for each meteringId to ensure idempotency.

πŸ“Š Metering Get Reports API

API Endpoint

GET https://mulerun.com/v1/metering/session/{sessionId}
This is a temporary endpoint that will be moved to https://api.mulerun.com/sessions/metering/session/{sessionId} in October 2025

Headers

NameTypeRequiredDescription
AuthorizationstringYesBearer token for authentication. Example: Authorization: Bearer <your_agent_key_here>

Path Parameters

Parameter NameTypeRequiredDescription
sessionIdstringYesUnique identifier of the session, passed via URL path

Response Format

βœ… Success Response

{
  "status": "success",
  "data": {
    "sessionId": "987e6543-e21b-45cd-b678-123456789abc",
    "sessionStatus": "completed",
    "reportCount": 3,
    "isFinalReported": true,
    "meteringRecords": [
      {
        "meteringId": "abc123efg-456h-789i-jklm-123nop456qr",
        "isFinal": false
      },
      {
        "meteringId": "def456hij-789k-012l-mnop-456qrs789tuv",
        "isFinal": false
      },
      {
        "meteringId": "ghi789klm-012n-345o-pqrs-789tuv012wxy",
        "isFinal": true
      }
    ]
  }
}


Field Descriptions

Top-Level Fields

FieldTypeDescription
statusstringFixed value "success", indicates the query was successful
dataobjectContains detailed session information

data Object Fields

FieldTypeDescription
sessionIdstringUnique identifier of the session
sessionStatusstringCurrent status of the session. Possible values: running (in progress), completed (ended normally), error (ended with error)
reportCountnumberNumber of successfully processed metering reports
isFinalReportedbooleanWhether the final report (isFinal=true) has been received
meteringRecordsarrayList of successfully processed metering records

Elements in meteringRecords Array

FieldTypeDescription
meteringIdstringUnique identifier from the metering API request
isFinalbooleanIndicates whether this is the final record

Session Status Descriptions

Status ValueDescription
runningThe session is active and can accept new metering requests
completedThe session has ended normally (either isFinal=true was reported or the session terminated properly)
errorThe session ended abnormally (e.g., platform failure or other errors)

Error Responses

❌ 400 Bad Request β€” Invalid request parameters

{
  "error": {
    "type": "invalid_request_error",
    "message": "Invalid request params"
  }
}

❌ 401 Unauthorized β€” Authentication failed

{
  "error": {
    "type": "authentication_error",
    "message": "Invalid authentication token"
  }
}

❌ 404 Not Found β€” Session does not exist

{
  "error": {
    "type": "not_found_error",
    "message": "Invalid session_id, session not found"
  }
}

❌ 403 Forbidden β€” Insufficient permissions

{
  "error": {
    "type": "permission_error", 
    "message": "Permission denied, not authorized to this session"
  }
}

❌ 500 Internal Server Error β€” Internal server error

{
  "error": {
    "type": "api_error",
    "message": "An internal error occurred. Please try again."
  }
}


Example Request

curl -X GET "https://mulerun.com/v1/metering/session/987e6543-e21b-45cd-b678-123456789abc" \
  -H "Authorization: Bearer <your_agent_key_here>"