The generation of contextID is internal and is present in jar files provided by webMethods. The way it works is like this:
When a service runs it generates a context id. If its a top level service, the root, parent and context id will be same, if its a 1st level child service then the context id will be different , but root and parent context id will be same. If its embedded at level 2 or 3 then all 3 will be different. The SAG code generates a context id whenever it spawns a thread or does an invoke of one process from another.
If you want to get the context id, you can do so using the code Mahesh gave earlier. You can get the context id either if you use the Exception Event manager and set the exception event handling to be synchronous or you can call the exception handling service below getLastError
#Integration-Server-and-ESB#webMethods#webMethods-General