The dynamic environments where Wireless Sensor Networks (WSNs) are being deployed, nowadays, necessitate the design of appropriate middleware architectures which provide flexible mechanisms to adapt application behavior while making wise utilization of the constrained resources. In combination with heterogeneity issues which usually appear in such networks, this results in high complexity of the application development typically involving the usage of a low or high level programming language in order to assure efficient operation of the network. To deal with these challenges, a modular middleware architecture is proposed which supports a programming abstraction based on the automation domain notion of function blocks (FBs). The network is (re)programmed with new applications in the form of mobile agents which are injected from a base station, while the Service Oriented Architecture (SOA) paradigm is adopted considering the function blocks as services distributed in the WSN nodes according to the resources of the underlying devices. Each agent is a schematic description of wirings between function blocks which are allocated by the middleware in the neighborhood of a target node, being in this way highly autonomous and adaptive, while presenting low resource utilization overhead as it is shown by an application case study.