The Oniwaban (御庭番) or niwaban (庭番) was a group of government-employed undercover agents (onmitsu), established by the 8th Tokugawa shōgun, Tokugawa Yoshimune (1684–1751). They were under the direct command of the shōgun and were in charge of undercover intelligence operations. In actuality, their work consisted more often of reporting any news about the city of Edo to the shōgun or remaining incognito to inspect and report on the states of affairs in the countryside. Their activities were comparable to those of the inspectors and general inspectors of the shogunate albeit under the direct orders from the shōgun.
Most historical plays and novels of the era depicted them as spies or ninjas, a tradition that continues to this time in popular culture. Oniwaban were male servers in the inner palace of the shōgun during the Edo shogunate where they served under the command of junior elders. They were the guards of the Edo castle who kept the security and checked every single thing for the sake of the Shogun's safety. There were restrictions placed on them regarding their contact with outsiders. They could only marry within their profession.[1]
Intelligence gathering was originally conducted by the Iga and Kōka mono guards, who arrived to Edo years after Tokugawa Ieyasu's escape through the Iga and Kōka regions in 1582, where they were placed under the command of Hattori Hanzo Masanari. However, as the Edo period progressed, the Iga and Kōka mono were tasked less with intelligence gathering, and more with guard work and criminal capture. When Yoshimune arrived from Kii, he had given his niwaban guards the same rank as the Iga mono guards. While relatively low in ranking, they could directly communicate with the shōgun. As such, some among their ranks were able to become close advisors or sent as diplomatic envoys.
The character "niwa" in their name, meaning garden or yard, refers to the rumor that they were quartered in the garden of Edo Castle.