{"record":{"id":"a01283d2262e6b00","repo":"mastra-ai/mastra","slug":"knowledge-tools-require-requestcontext-organizatio","errorCode":null,"errorMessage":"Knowledge tools require requestContext.organizationId.","messagePattern":"Knowledge tools require requestContext\\.organizationId\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/memory/src/processors/observational-memory/subconscious/knowledge-tools.ts","lineNumber":36,"sourceCode":"\ntype KnowledgeToolsMemory = {\n  storage: {\n    getStore(name: 'knowledge'): Promise<KnowledgeStorage | undefined>;\n  };\n  getKnowledgeSemanticIndex(): Promise<KnowledgeSemanticIndexCoordinator>;\n};\n\ntype KnowledgeToolContext = {\n  agent?: { threadId?: string; resourceId?: string };\n  requestContext?: { get(key: string): unknown };\n};\n\nfunction resolveScope(context: KnowledgeToolContext | undefined): KnowledgeScope {\n  const organizationId = context?.requestContext?.get('organizationId');\n  const resourceId = resolveKnowledgeResourceId(context?.requestContext, context?.agent?.resourceId);\n  const threadId = context?.agent?.threadId;\n  if (typeof organizationId !== 'string' || !organizationId.trim()) {\n    throw new Error('Knowledge tools require requestContext.organizationId.');\n  }\n  if (!resourceId) throw new Error('Knowledge tools require an active resourceId.');\n  if (!threadId) throw new Error('Knowledge tools require an active threadId.');\n  return [`org:${organizationId}`, `resource:${resourceId}`, `thread:${threadId}`];\n}\n\nasync function getKnowledgeStore(memory: KnowledgeToolsMemory): Promise<KnowledgeStorage> {\n  const store = await memory.storage.getStore('knowledge');\n  if (!store) throw new Error('Knowledge tools require a configured knowledge storage domain.');\n  return store;\n}\n\nfunction normalizeLimit(limit: number | undefined): number {\n  return Math.min(Math.max(limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);\n}\n\nfunction serializeRecord(record: KnowledgeRecord) {\n  return {","sourceCodeStart":18,"sourceCodeEnd":54,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/memory/src/processors/observational-memory/subconscious/knowledge-tools.ts#L18-L54","documentation":"Subconscious knowledge tools resolve an access scope from requestContext: organizationId, resourceId, and threadId. The scope is [org:..., resource:..., thread:...]; without a non-empty organizationId string on requestContext the tools cannot scope knowledge access, so resolveScope throws before any storage access.","triggerScenarios":"Invoking a knowledge tool (via agent tool call or direct call) where context.requestContext is undefined, or requestContext.get('organizationId') returns undefined/non-string/whitespace-only.","commonSituations":"Calling the memory/agent API outside a request lifecycle without building a requestContext; forgetting to set organizationId in middleware; multi-tenant setups where org id propagation was recently added; unit tests invoking tools without a request context.","solutions":["Populate requestContext with a non-empty organizationId before invoking the agent/tools, e.g. requestContext.set('organizationId', orgId).","Ensure the framework passes the same requestContext into memory/knowledge tool execution (agent.run/stream options).","In tests, construct a RequestContext with organizationId set, matching production middleware."],"exampleFix":"// before\nawait agent.stream(prompt); // no request context\n// after\nconst requestContext = new RequestContext();\nrequestContext.set('organizationId', 'org_123');\nawait agent.stream(prompt, { requestContext });","handlingStrategy":"validation","validationCode":"const orgId = requestContext?.get('organizationId');\nif (typeof orgId !== 'string' || !orgId.trim()) {\n  throw new Error('knowledge tools invoked without organizationId');\n}","typeGuard":"function hasKnowledgeScope(ctx?: { requestContext?: { get(k: string): unknown } }): boolean {\n  const org = ctx?.requestContext?.get('organizationId');\n  return typeof org === 'string' && org.trim().length > 0;\n}","tryCatchPattern":"try {\n  await knowledgeTool.invoke({ requestContext, agent });\n} catch (e) {\n  if (e instanceof Error && e.message === 'Knowledge tools require requestContext.organizationId.') {\n    requestContext.set('organizationId', resolveOrgFromAuth());\n    // retry once with context populated\n  } else throw e;\n}","preventionTips":["Set organizationId in auth middleware for every agent request.","Use a typed RequestContext wrapper that requires organizationId.","Assert context completeness in integration tests.","Fail early at route level when org id is absent."],"tags":["configuration","request-context","multi-tenancy","knowledge-tools"],"backgroundTag":"missing-request-context","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}