{"record":{"id":"f6163e4e49237579","repo":"mastra-ai/mastra","slug":"agent-with-id-id-already-exists","errorCode":null,"errorMessage":"Agent with id ${id} already exists","messagePattern":"Agent with id (.+?) already exists","errorType":"http","errorClass":"HTTPException","httpStatus":409,"severity":"error","filePath":"packages/server/src/server/handlers/stored-agents.ts","lineNumber":606,"sourceCode":"\n      const agentsStore = await storage.getStore('agents');\n      if (!agentsStore) {\n        throw new HTTPException(500, { message: 'Agents storage domain is not available' });\n      }\n\n      // Derive ID from name if not explicitly provided\n      const id = providedId || toSlug(name);\n\n      if (!id) {\n        throw new HTTPException(400, {\n          message: 'Could not derive agent ID from name. Please provide an explicit id.',\n        });\n      }\n\n      // Check if agent with this ID already exists\n      const existing = await agentsStore.getById(id);\n      if (existing) {\n        throw new HTTPException(409, { message: `Agent with id ${id} already exists` });\n      }\n\n      // Force authorId from the authenticated caller; ignore any body-provided value.\n      // No owner = always public (no auth / no user context).\n      // With an owner, respect the client's choice, defaulting to 'private'.\n      const authorId = getCallerAuthorId(requestContext) ?? undefined;\n      const visibility = authorId ? (bodyVisibility ?? 'private') : 'public';\n\n      // Reject oversized avatar images before writing to storage.\n      validateMetadataAvatarUrl(metadata);\n\n      // Model policy enforcement is intentionally not done on save: each UI\n      // surface gates its own model picker via ModelPolicyProvider, and the\n      // policy is surface-scoped (builder vs editor). Re-introducing a single\n      // server-side check here would either over-enforce on the editor or\n      // under-enforce on the builder until per-surface enforcement lands.\n\n      const resolvedBrowser = await resolveBrowserField(browser, mastra);","sourceCodeStart":588,"sourceCodeEnd":624,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/server/src/server/handlers/stored-agents.ts#L588-L624","documentation":"Thrown with HTTP 409 (Conflict) when creating a stored agent whose derived or provided `id` already exists in the agents store — `agentsStore.getById(id)` returned an existing record. Agent IDs are unique keys, so the create is refused to avoid silently overwriting an existing agent.","triggerScenarios":"POST /api/agents where the explicit `id` in the body, or the slug derived from `name`, matches an already-stored agent (draft or published).","commonSituations":"Re-running a seed/bootstrap script that creates agents with fixed IDs; two users independently naming agents the same thing; retrying a create after a network timeout when the first request actually succeeded; an ID derived from a very generic agent name like 'assistant'.","solutions":["Check existence first with GET the agent by ID and use the update endpoint instead of create if it exists","Provide a different explicit `id` for the new agent","Rename the agent so the derived slug is unique","Make create scripts idempotent: catch 409 and treat as 'already created' or upsert via update"],"exampleFix":"// before\nawait createStoredAgent({ id: 'support-bot', name: 'Support Bot' }); // 409 on rerun\n\n// after\nconst existing = await getStoredAgent('support-bot');\nif (existing) {\n  await updateStoredAgent('support-bot', { instructions });\n} else {\n  await createStoredAgent({ id: 'support-bot', name: 'Support Bot' });\n}","handlingStrategy":"validation","validationCode":"const existing = await getStoredAgent(id).catch(() => null);\nif (existing) {\n  return updateStoredAgent(id, patch); // upsert-style\n}","typeGuard":"null","tryCatchPattern":"try {\n  await createStoredAgent(input);\n} catch (e) {\n  if (isHttpError(e) && e.status === 409) {\n    return updateStoredAgent(input.id, input); // treat as upsert\n  }\n  throw e;\n}","preventionTips":["Make seed/bootstrap scripts idempotent (check-then-create or upsert)","Use unique, prefixed IDs for generated agents (e.g. `org:team:assistant`)","Generate IDs with UUIDs/nanoids when names are user-supplied and may collide"],"tags":["conflict","http-409","duplicate","unique-constraint"],"backgroundTag":"duplicate-resource-conflict","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}