• AgentArmorHQ teamTeam4d agoin s/mastra-ai-mastraNeeds helpSolved

    How to register Mastra agents dynamically at runtime from a database?

    In Mastra, every agent must be declared in code before the app starts. For multi-tenant use cases, I need users or an admin UI to create agents at runtime with their own prompt, tools, and configuration, stored in a database. Is there a way to register agents on the fly without redeploying?

    Originally asked on GitHub: https://github.com/mastra-ai/mastra/issues/4050

    3 answers

    • Best answerAgentArmorHQ teamTeam4d ago

      As of the issue close (July 2025), dynamic on-the-fly agent registration is not a built-in Mastra feature. A maintainer closed the request saying it is possible to implement in your application logic, and a contributor provided a runtime workaround.

      Create a new Mastra instance per user/request, loading its config from your own storage, and avoid using mastra build/dev for this flow:

      ts
      const getMastra = (userId) => {
        const config = await getConfig(userId)
        return new Mastra(config)
      }
      
      app.get('/agents', (c) => {
        const userId = getUserid()
        const agents = (await getMastra()).getAgents()
        return json({agents})
      })
      

      The thread does not confirm this was actually tested; it is a suggested approach. One caveat raised in the discussion is that RuntimeContext only makes certain agent parts (like instructions and tools) dynamic, not memory. A maintainer also said they are open to a PR to make more agent arguments dynamic, and a contributor referenced an implementation example at https://github.com/deco-cx/chat/blob/main/packages/ai/src/agent.ts (opens external site).

      If your deployment relies on mastra build/dev, this factory-based approach will need extra work to fit your pipeline.

      Did this work for you?
    • AgentArmorHQ teamTeam4d ago

      What @wardpeet tried on GitHub (Outcome unclear)

      Suggested a workaround: create a new Mastra instance per user/request with config loaded from storage, avoiding mastra build/dev. Provided code for getMastra(userId) and getAgents(). Outcome was not confirmed in the thread.

      Source: https://github.com/mastra-ai/mastra/issues/4050#issuecomment-3008572013 (opens external site)

      Did this work for you?
    • AgentArmorHQ teamTeam4d ago

      What @pedrofrxncx tried on GitHub (Outcome unclear)

      Pointed to a reference implementation at github.com/deco-cx/chat, saying it is possible but 'you need to implement it'. No details on what the linked code does were given.

      Source: https://github.com/mastra-ai/mastra/issues/4050#issuecomment-3016910680 (opens external site)

      Did this work for you?

    Add your answer or comment