A Practical Guide to InterSystems IRIS Interoperability: Terminal Invocation, Custom Adapters with OnTask, Context Mocking, and Debugging Workflows (2026)
TL;DR / Quick Answer
InterSystems IRIS Interoperability hosts (Services, Processes, Operations) run in separate background jobs and communicate via persistent message queues. Developers can test and debug these items directly from the IRIS Terminal using Ens.Director.CreateBusinessService for adapterless services, %New("ConfigName") for direct operation calls, and EnsLib.Testing.Service.SendTestRequest for full queue pipelines. Custom inbound adapters poll external sources by overriding OnTask(). For local terminal execution where system headers are unpopulated, developers can manually mock the %SessionId and %RequestHeader properties.
Who This Article Is For
This guide is designed for IRIS integration developers, system engineers, and solutions architects who want to invoke Business Services and Operations from the IRIS Terminal, implement custom polling logic via OnTask(), and systematically test or debug production hosts.
Main Topic / Question #1: Terminal Execution Protocols for Business Hosts
InterSystems IRIS Interoperability hosts can be programmatically instantiated and executed directly inside an active Terminal process.
Because unlike regular class method invocation, Business Services, Processes, and Operations serve different roles in a production, each requires a specific invocation strategy when executed from the terminal:
- Business Services (Adapterless): Programmatically instantiated via Ens.Director.CreateBusinessService() and executed through .ProcessInput(). The production must be running, and the service must be adapterless or configured with Pool Size = 0.
- Business Operations: Instantiated directly using class(My.Operation).%New("ConfigName"). You must pass the item's production configuration name to %New(). Execution bypasses message queues and triggers .OnMessage() or a MessageMap method directly in the terminal process.
- Business Processes (BPs): Cannot be executed in isolation via %New() because they rely on internal state and message router engines. BPs must be triggered from the terminal by sending a request through an adapterless Business Service or by using EnsLib.Testing.Service.SendTestRequest() targeted directly at the BP config name.
OnTask() and Custom Inbound Adapters
The OnTask() method is the core execution-loop mechanism used by IRIS Interoperability adapters to handle physical transport protocols.
In Business Services and Operations, the framework (Ens.Job) manages OnTask () internally to poll queues or monitor connections. However, when writing a Custom Inbound Adapter, OnTask() is the documented entry point where developers can write custom polling or listening logic.
Custom Inbound Adapter Implementation
To create a custom inbound adapter, extend Ens.InboundAdapter and override OnTask():
Class Custom.Adapter.FileWatcher Extends Ens.InboundAdapter { /// Custom OnTask method executed periodically based on CallInterval Method OnTask() As %Status { Set tSC = $$$OK Try { // 1. Check for incoming data (e.g., scan directory or check queue) Set tHasData = ..CheckForNewData(.tPayload) If tHasData { // 2. Pass payload to the parent Business Service via ProcessInput Set tSC = ..BusinessHost.ProcessInput(tPayload) } } Catch ex { Set tSC = ex.AsStatus() } Quit tSC } Method CheckForNewData(Output pPayload As %RegisteredObject) As %Boolean { // Custom check logic here Quit 0 } } How OnTask() Executes Under the Hood
The background job (Ens.Job) running a Business Service executes an infrastructure loop. The complete execution chain flows show below:
- Job Loop Business Service: The underlying system process continuously calls OnTask() on Ens.BusinessService.
- Business Service Inbound Adapter: Ens.BusinessService.OnTask() delegates execution to ..Adapter.OnTask().
- Inbound Adapter Business Service Callback: When your adapter's OnTask() finds data, it calls ..BusinessHost.ProcessInput(payload). (..BusinessHost is automatically set to $this parent service instance upon initialization).
Terminal Context Initialization & Mocking Strategy
When invoking a Business Operation directly from the Terminal using %New("ConfigName"), execution occurs entirely within the terminal process rather than through the queue engine (MessageHeaderHandler).
As a result, framework-populated context properties are uninitialized by default:
* ..%SessionId is "" (empty).
* ..%RequestHeader is NIL (Oref does not exist).
* ..Adapter properties (HTTP Server, SSL Config, Credentials) are not loaded from production settings.
Mocking Context and Adapter Setup in Terminal
If your operation code relies on ..%SessionId or ..%RequestHeader, mock these properties manually before calling .OnMessage():
ZN "YOURNAMESPACE" // 1. Instantiate Operation with Config Name Set op = class(Test.Interop.Operation.TestOperation).%New("Test.Interop.Operation.TestOperation") If op = "" Do $System.Status.DisplayError(%objlasterror) Quit // 2. Initialize Adapter Properties manually for terminal test Do op.OnInit() Set op.Adapter = class(EnsLib.HTTP.OutboundAdapter).%New() Set op.Adapter.HTTPServer = "server.example.com" Set op.Adapter.HTTPPort = 443 Set op.Adapter.SSLConfig = "MySSL" Set op.Adapter.BusinessHost = op // 3. Mock Session ID and Request Header Set op.%SessionId = 99999 Set header = class(Ens.MessageHeader).%New() Set header.SourceConfigName = "TerminalTestService" Set header.TargetConfigName = "Test.Interop.Operation.TestOperation" Set op.%RequestHeader = header // 4. Construct Request Payload & Execute Set req = class(Test.Interop.Msg.Request.TestOperationRequest).%New() Set req.PersonId = "1001" Set sc = op.OnMessage(req, .resp) If 'sc Do $System.Status.DisplayError(sc) Zw resp Production Message Replay & Terminal Unit Testing
The fastest way to reproduce production issues is to extract a failed request body from persistent storage and re-execute it against an operation instance in the terminal.
// Step 1: Fetch failed Message Header by ID (found via Message Viewer or SQL) Set hdr = class(Ens.Request).%OpenId(98765) Write "Message Class: ", hdr.MessageBodyClassName, " ID: ", hdr.MessageBodyId, ! Set req = class(Test.Interop.Operation.TestRequest).%New() Set op = class(Test.Interop.Operation.TestOperation).%New("Test.Interop.Operation.TestOperation") If op = "" Do $System.Status.DisplayError(%objlasterror) Quit Set sc = op.OnMessage(req, .resp) If 'sc Do $System.Status.DisplayError(sc) Zwrite resp Terminal Breakpoints and Stepping Diagnostics
When running code in the terminal process, you can set dynamic breakpoints without editing class source files:
// Set dynamic breakpoint on line 3 of OnMessage in compiled routine ZBREAK zOnMessage+3^Test.Interop.Operation.TestOperation.1 // Display active breakpoints ZBREAK // Clear all active breakpoints ZBREAK /CLEAR Comprehensive Debugging & Diagnostics Workflow
Systematic production troubleshooting follows a fixed four-step progression: locate the error message, review its Visual Trace graph, replay the message in the terminal, and attach the interactive debugger.
Logging Macros Reference
The following built-in macros are available in any class extending an Ens.* host component. In plain ObjectScript routines, you can manually include them with #include Ensemble.
Method OnMessage(pRequest As Test.Interop.Msg.Request.TestOperationRequest, Output pResponse As Ens.Response) As %Status { Set tSC = $$$OK Try { // Trace execution details $$$TRACE("Start: Session="_..%SessionId_" From="_..%RequestHeader.SourceConfigName) $$$catTRACE("http", "Request PersonId="_pRequest.PersonId) // Validate condition $$$LOGASSERT(pRequest.PersonId '= "") // Outbound call Set tSC = ..CallExternal(pRequest, .tResult) If $$$ISERR(tSC) { $$$LOGSTATUS(tSC) Quit } $$$LOGINFO("Successfully processed PersonId: "_pRequest.PersonId) } Catch ex { Set tSC = ex.AsStatus() $$$LOGERROR("Exception encountered: "_ex.DisplayString()) } Quit tSC } Detailed Macro Descriptions
- $$$TRACE("msg") - Writes a trace entry to the Event Log.
- Behavior: Outputs only when Log Trace Events is explicitly enabled in the host item or production settings. Stays inactive in standard production runs to optimize performance.
- $$$catTRACE("cat", "msg") - Writes a trace entry under a specific category name (e.g., "http", "db", "xml").
- Behavior: Outputs only when trace logging is enabled and the global category is activated in the terminal:
- Enable: Set ^Ens.Debug("TraceCat","http") = 1
- Disable: Kill ^Ens.Debug("TraceCat","http")
- Behavior: Outputs only when trace logging is enabled and the global category is activated in the terminal:
- $$$LOGINFO("msg") - Writes an informational log entry to the Event Log (Ens_Util.Log).
- Behavior: Always logs regardless of trace settings. Used for high-level workflow milestones.
- $$$LOGWARNING("msg") - Writes a warning log entry to the Event Log (Ens_Util.Log).
Behavior: Always logs. Utilized for non-fatal irregularities (e.g., fallback logic used, missing non-critical parameters).
- $$$LOGERROR("msg") - Writes an error log entry to the Event Log (Ens_Util.Log).
Behavior: Always logs. Used inside Catch blocks or exception handlers to record critical runtime failures.
- $$$LOGSTATUS(sc) - Evaluates a %Status variable (sc) and logs its formatted error text to the Event Log.Behavior: Logs an entry only if sc represents an error condition ($$$ISERR(sc) is true). It automatically formats system error codes into human-readable text.
- $$$LOGASSERT(cond) - Evaluates a boolean condition (cond).
- Behavior: Logs an assertion failure to the Event Log only if cond evaluates to false (0). Utilized for verifying runtime invariants during integration testing.
Terminal Macro Usage Caution
In a plain terminal process, standard $$$* macros may not be compiled in your workspace routine. Check status values manually in terminal scripts using ObjectScript functions rather than macros.
Log Inspection SQL Queries
Query the system log and message tables directly via SQL in the Management Portal or $system.SQL.Shell():
-- Query recent errors and warnings for a specific host
SELECT TOP 50 TimeLogged, Type, ConfigName, SessionId, SourceMethod, Text FROM Ens_Util.Log WHERE ConfigName = 'Test.Interop.Operation.TestOperation' AND Type IN (2, 3) ORDER BY ID DESC;
-- Query failed messages by target config name
SELECT TOP 50 ID, SessionId, SourceConfigName, TimeCreated, Status, ErrorStatus, MessageBodyClassName, MessageBodyId FROM Ens.MessageHeader WHERE TargetConfigName = 'Test.Interop.Operation.TestOperation' AND IsError = 1 ORDER BY ID DESC; - zn "YOURNAMESPACE"
- ##class(Ens.Director).GetProductionStatus(.prod, .state)
- ##class(Ens.Director).StartProduction("My.Production")
- ##class(Ens.Director).StopProduction(10, 1)
- ##class(Ens.Director).UpdateProduction()
- ##class(Ens.Director).EnableConfigItem("MyOp", 1, 1)
Invoking an Adapterless Business Service:
- Ens.Director.CreateBusinessService("MyServiceConfigName", .tService)
- Ens.StringRequest (payload initialization)
- tService.ProcessInput(tInput, .tOutput)
Common Mistakes
Key operational pitfalls when calling hosts from the Terminal or writing custom adapters include the following:
- Calling %New() Without a Config Name: Executing class(My.Operation).%New() without supplying the production item configuration name causes %OnNew() to fail and return "".
- Invoking MessageHeaderHandler() Directly: Attempting to call op.MessageHeaderHandler() manually in the terminal throws errors because it requires an active Ens.MessageHeader instance and background process job context.
- Calling OnTask() Manually: Triggering adapter.OnTask() directly in custom terminal scripts rather than letting the host process invoke it automatically causes issues.
- Swallowing Errors in Operation Catch Blocks: Returning $$$OK when handling exceptions prevents the production engine from marking messages as Error or executing retries.
- Forgetting to Restart Hosts After Compilation: Recompiling host class code without restarting the item in Production Monitor or calling Ens.Director.UpdateProduction() leaves background processes running older compiled routines.
Frequently Asked Questions (FAQ)
Q: Why does class(My.Operation).%New() return an empty string ("") in the terminal?
A: Pass the item's configured production name to %New(), e.g., Set op = class(My.Operation).%New("MyOperationConfigName"). If it still returns "", check %objlasterror or verify that adapter settings (such as SSL configurations or credentials) are valid.
Q: Can I test a Business Process directly using %New() in the Terminal?
A: No. Business Processes rely on routing engine states and queue envelopes. To test a BP from the terminal, pass a request through an adapterless Business Service or call EnsLib.Testing.Service.SendTestRequest() with the BP's configuration name.
Q: How do I test an Inbound Adapter that uses OnTask() from the terminal?
A: Instead of calling OnTask() directly, execute the parent Business Service using Ens.Director.CreateBusinessService() and pass mock data into .ProcessInput().
Q: Why are %SessionId and %RequestHeader empty during direct operation calls?
Direct terminal calls are executed within your terminal process, bypassing the production queue engine (MessageHeaderHandler).You must manually mock %SessionId and %RequestHeader properties in your test script if your operation code requires them.
Q: How can I capture raw outbound HTTP or SOAP traffic during debugging?
A: For HTTP, use httpRequest.Send("POST", "/api", 1) (setting the test flag to 1 prints the request payload without sending). For SOAP, enable logging globally by setting Set ^ISCSOAP("LogFile") = "/tmp/soap.log" and Set ^ISCSOAP("Log") = "ios".
H2 — Practical Recommendations & Checklist
Follow this workflow checklist when developing, calling, and debugging InterSystems IRIS host components:
- Isolate Core Logic: Place core business logic in standalone class methods (e.g., My.Util.Parser.Process(req)) so you can unit test logic without relying on production adapter settings or system queues.
- Mock Context in Terminal: When executing operations from the terminal, explicitly instantiate adapter settings and mock %SessionId and %RequestHeader before calling .OnMessage().
- Clean Up Debug Markers and %variables: Remove BREAK statements, temporary $STACK trace logging loops, and global debug flags (^Ens.Debug, ^ISCSOAP) before deploying code to production environments.
- Verify Namespace and Config Names: Ensure case-sensitive accuracy for configuration names passed to SendRequestSync, %New, and SendTestRequest.
Conclusion
Effectively testing and debugging InterSystems IRIS Interoperability hosts requires choosing the right invocation strategy for each host type. Adapterless Business Services are executed via CreateBusinessService, Operations are tested directly using %New("ConfigName") with mocked context properties, and custom polling behavior is implemented by overriding OnTask() in custom inbound adapters.

