Task Loop
openmcp-sdk builds agents using a task loop mechanism and allows users to interact with them. If users need real-time control over this task loop, they can register corresponding hook functions through the events provided by openmcp-sdk.
Taking the example from Quick Deploy, you can obtain the object controlling the task loop with the following code:
typescript
import { OmAgent } from '../openmcp-sdk/service/sdk';
const agent = new OmAgent();
agent.loadMcpConfig('./mcpconfig.json');
const loop = await agent.getLoop();WARNING
Registering hooks and obtaining the loop must be completed before agent.ainvoke!
Through this loop object, we can register the following hooks:
registerOnChunk: Triggered when the model returns a chunkregisterOnDone: Triggered when the task is completedregisterOnError: Triggered when the task encounters an errorregisterOnEpoch: Triggered at the start of each task epochregisterOnToolCall: Triggered before calling a tool functionregisterOnToolCalled: Triggered after calling a tool functionregisterOnTokenConsumption: Triggered after openmcp calculates token consumption and price, etc., which can be used to obtain the cost of the current agent loop call.
These hook functions accept a callback function, which will be called when the corresponding event is triggered.
typescript
loop.registerOnChunk((chunk) => {
console.log('⚙️ Agent Chunk', chunk);
});
loop.registerOnDone(() => {
console.log('⚙️ Agent Done');
});
loop.registerOnError((err) => {
console.log('⚙️ Agent Error', err);
});
loop.registerOnEpoch(() => {
console.log('⚙️ Agent Epoch');
});
loop.registerOnToolCall((toolCall) => {
console.log('⚙️ Agent Tool Call', toolCall);
return toolCall;
});
loop.registerOnToolCalled((toolCalled) => {
console.log('⚙️ Agent Tool Called', toolCalled);
return toolCalled;
});
loop.registerOnTokenConsumption((result) => {
console.log('⚙️ Agent Token Consumption', result);
});