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
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
Mastrainstance per user/request, loading its config from your own storage, and avoid usingmastra build/devfor this flow:tsconst 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
RuntimeContextonly 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?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?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?
Related questions
- Mastra dev fails on uncompiled workspace TypeScript dependencies
- Mastra AI SDK v5: MastraClient 'Failed to parse stream string' and Cloud ENOENT build errors — how to fix?
- Mastra A2A sendStreamingMessage fails: Unexpected non-whitespace character after JSON
- Does Mastra support Zod v4 yet?
- Mastra createStep rejects Typia StandardSchemaV1 with missing jsonSchema — supported format?