@mastra/mcp-docs-server 1.3.13-alpha.9 → 1.3.14-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/.docs/docs/agents/code-mode.md +4 -0
  2. package/.docs/docs/agents/tools.md +12 -2
  3. package/.docs/docs/auth/custom-auth-provider.md +66 -0
  4. package/.docs/docs/auth/jwt.md +1 -1
  5. package/.docs/docs/connections/mcp.md +4 -65
  6. package/.docs/docs/evals/overview.md +4 -0
  7. package/.docs/docs/guides/authentication-identity.md +13 -1
  8. package/.docs/docs/harness/schedules.md +1 -1
  9. package/.docs/docs/knowledge/scopes-and-access.md +1 -1
  10. package/.docs/docs/memory/multi-user-threads.md +57 -127
  11. package/.docs/docs/memory/observational-memory.md +196 -756
  12. package/.docs/docs/memory/overview.md +4 -0
  13. package/.docs/docs/observability/feedback.md +5 -7
  14. package/.docs/docs/sandbox/overview.md +2 -0
  15. package/.docs/docs/sandbox/search.md +25 -0
  16. package/.docs/docs/server/mcp.md +347 -0
  17. package/.docs/docs/server/overview.md +1 -0
  18. package/.docs/docs/server/request-context.md +35 -0
  19. package/.docs/docs/server/server-adapters.md +2 -0
  20. package/.docs/docs/studio/auth.md +5 -1
  21. package/.docs/docs/studio/deployment.md +0 -1
  22. package/.docs/docs/studio/editor.md +17 -0
  23. package/.docs/docs/studio/overview.md +5 -5
  24. package/.docs/docs/workflows/scheduled-workflows.md +26 -5
  25. package/.docs/integrations/sandboxes/docker.md +39 -0
  26. package/.docs/integrations/sandboxes/e2b.md +1 -1
  27. package/.docs/integrations/voice/openai.md +2 -2
  28. package/.docs/models/gateways/custom-gateways.md +74 -44
  29. package/.docs/reference/agents/generate.md +1 -1
  30. package/.docs/reference/agents/generateLegacy.md +7 -23
  31. package/.docs/reference/auth/auth0.md +2 -0
  32. package/.docs/reference/auth/clerk.md +4 -0
  33. package/.docs/reference/auth/jwt.md +30 -2
  34. package/.docs/reference/cli/mastra.md +74 -6
  35. package/.docs/reference/client-js/observability.md +13 -5
  36. package/.docs/reference/configuration.md +64 -0
  37. package/.docs/reference/connect/tools.md +59 -0
  38. package/.docs/reference/editor/mastra-editor.md +1 -1
  39. package/.docs/reference/index.md +2 -0
  40. package/.docs/reference/knowledge/knowledge-class.md +1 -1
  41. package/.docs/reference/knowledge/knowledge-memory-scopes.md +44 -4
  42. package/.docs/reference/knowledge/scope-declarations.md +7 -3
  43. package/.docs/reference/memory/observational-memory.md +350 -151
  44. package/.docs/reference/observability/feedback.md +57 -14
  45. package/.docs/reference/observability/tracing/advanced-queries.md +3 -1
  46. package/.docs/reference/observability/tracing/exporters/langfuse.md +24 -1
  47. package/.docs/reference/observability/tracing/exporters/mastra-platform-exporter.md +19 -16
  48. package/.docs/reference/observability/tracing/exporters/otel.md +1 -1
  49. package/.docs/reference/observability/tracing/interfaces.md +2 -2
  50. package/.docs/reference/observability/tracing/spans.md +7 -1
  51. package/.docs/reference/processors/processor-interface.md +23 -0
  52. package/.docs/reference/rag/chunk.md +1 -1
  53. package/.docs/reference/rag/graph-rag-guide.md +3 -1
  54. package/.docs/reference/schedules/overview.md +25 -5
  55. package/.docs/reference/server/builtin-mcp-tools.md +135 -0
  56. package/.docs/reference/server/dispatch-route.md +124 -0
  57. package/.docs/reference/server/elysia-adapter.md +1 -1
  58. package/.docs/reference/server/express-adapter.md +17 -11
  59. package/.docs/reference/server/fastify-adapter.md +1 -1
  60. package/.docs/reference/server/hono-adapter.md +1 -1
  61. package/.docs/reference/server/invoke-route.md +10 -0
  62. package/.docs/reference/server/koa-adapter.md +1 -1
  63. package/.docs/reference/server/nestjs-adapter.md +1 -1
  64. package/.docs/reference/streaming/agents/stream.md +1 -1
  65. package/.docs/reference/tools/mcp-server.md +2 -0
  66. package/.docs/reference/workspace/factory-sandbox.md +20 -1
  67. package/.docs/reference/workspace/platform-sandbox.md +1 -1
  68. package/package.json +5 -5
@@ -371,11 +371,17 @@ const result = await mastraClient.deleteTraces({
371
371
  traceIds: ['trace-1', 'trace-2'],
372
372
  })
373
373
 
374
- console.log(result.success)
374
+ if ('accepted' in result) {
375
+ console.log('Deletion requested')
376
+ } else {
377
+ console.log(result.success)
378
+ }
375
379
  ```
376
380
 
377
381
  Each request accepts up to 1,000 trace IDs and no tenant scope fields. Signals that aren't linked to a trace are preserved. Traces created by experiments are deleted like any other trace.
378
382
 
383
+ The client supports two response shapes: OSS returns `{ success: true }` after its delete operation, while a Platform backend that supports queued batch deletion returns `202 { accepted: true }` after accepting cleanup. Acceptance doesn't mean records have disappeared from reads, so check the response before reporting deletion as complete. Using these client methods with Platform requires a deployment that supports the batch deletion endpoints.
384
+
379
385
  ## Scoring traces
380
386
 
381
387
  Score specific traces using registered scorers for evaluation:
@@ -432,7 +438,7 @@ const response = await mastraClient.createScore({
432
438
 
433
439
  ## Feedback
434
440
 
435
- Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the configured API server. Create methods support OSS and Platform. Full replacement uses Platform's PUT endpoint. See the [feedback guide](https://mastra.ai/docs/observability/feedback) for examples and the [feedback reference](https://mastra.ai/reference/observability/feedback) for full schemas.
441
+ Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the configured API server. Create methods support OSS and Platform. Full replacement is supported by Platform and OSS servers with feedback replacement support. See the [feedback guide](https://mastra.ai/docs/observability/feedback) for examples and the [feedback reference](https://mastra.ai/reference/observability/feedback) for full schemas.
436
442
 
437
443
  ### Get feedback by ID
438
444
 
@@ -492,9 +498,9 @@ Create responses contain `success` and optional `data` with the generated or sup
492
498
 
493
499
  Explicit modes require server support. Older servers may ignore `contextMode`. Deploy Platform's supplied-context support before sending `"provided"` there.
494
500
 
495
- ### Replacing feedback on Platform
501
+ ### Replacing feedback
496
502
 
497
- `replaceFeedback()` sends a full replacement to `PUT /api/observability/feedback/:feedbackId`. Include the original `feedbackId`, `traceId`, and normalized `timestamp`, along with all feedback fields to retain. This method targets Platform. OSS server doesn't implement this replacement endpoint.
503
+ `replaceFeedback()` sends a full replacement to `PUT /api/observability/feedback/:feedbackId`. Include the original `feedbackId`, `traceId`, and normalized `timestamp`, along with all feedback fields to retain. Platform and OSS servers with feedback replacement support accept this method. OSS returns `501` when its storage adapter doesn't support replacement. For OSS, check `capabilities.feedbackReplacement` before offering edits. A missing capability means unavailable.
498
504
 
499
505
  ```typescript
500
506
  await mastraClient.replaceFeedback({
@@ -509,7 +515,7 @@ await mastraClient.replaceFeedback({
509
515
  })
510
516
  ```
511
517
 
512
- Use the normalized timestamp from the create response's `data` when available. A changed timestamp identifies a different Platform record. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable automatic retries.
518
+ Use the normalized timestamp from the create response's `data` when available. OSS rejects changes to the original trace or timestamp with `409`. Platform uses the timestamp as part of record identity, so preserve it there too. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable automatic retries.
513
519
 
514
520
  ### Deleting feedback and scores
515
521
 
@@ -529,6 +535,8 @@ await mastraClient.deleteScores({
529
535
  })
530
536
  ```
531
537
 
538
+ Both methods return `{ success: boolean }` from OSS or `{ accepted: true }` from a Platform backend that supports queued batch deletion. See [Deleting traces](#deleting-traces) for response handling. Accepted records can remain readable until cleanup runs. Platform uses authenticated organization/project scope, which request-body scope fields can't override.
539
+
532
540
  ### Listing feedback
533
541
 
534
542
  Retrieve paginated feedback records with optional filters:
@@ -720,6 +720,70 @@ export const mastra = new Mastra({
720
720
  })
721
721
  ```
722
722
 
723
+ ### server.mcp
724
+
725
+ **Type:** `object`\
726
+ **Default:** `undefined`
727
+
728
+ Configures the [built-in MCP server](https://mastra.ai/docs/server/mcp) that exposes your agents, workflows, and tools at `/api/mcp`.
729
+
730
+ | Property | Type | Default | Description |
731
+ | ------------ | ----------------------------------------------------------------------------------------------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
732
+ | `enabled` | `boolean \| 'dev'` | `'dev'` | `'dev'` serves the endpoint under `mastra dev`, and in production only when `server.auth` is configured. `true` always serves it and logs a warning when no auth is configured. `false` never serves it. |
733
+ | `path` | `string` | `'/mcp'` | Path of the endpoint, mounted under the API prefix. Each segment can use letters, digits, `-`, `.`, `_`, and `~`. Invalid paths and paths that collide with the `MCPServer` routes or any other server route fall back to `/mcp` and log an error. |
734
+ | `toolsets` | `('agents' \| 'workflows' \| 'tools' \| 'memory' \| 'observability' \| 'observability_analytics' \| 'stored_agents')[]` | All toolsets | Toolsets to serve. Clients can narrow this per request with `?toolsets=` or the `X-MCP-Toolsets` header. |
735
+ | `enumLimit` | `number` | `25` | Up to this many visible agents or workflows are listed as an enum on the id argument, and up to this many tools get an individual `tool_<id>` tool. |
736
+ | `featured` | `{ agents?: string[]; workflows?: string[] }` | `undefined` | Agents and workflows that also get a dedicated `agent_<id>` or `workflow_<id>` tool. |
737
+ | `readOnly` | `boolean` | `false` | Only serve tools whose backing route is a read operation. Clients can also request this with `?readonly=1` or the `X-MCP-Readonly` header. |
738
+ | `include` | `{ agents?: string[]; workflows?: string[]; tools?: string[] }` | `undefined` | When set for a primitive type, only these are exposed. Each entry matches a primitive's `id` or its registration key. |
739
+ | `exclude` | `{ agents?: string[]; workflows?: string[]; tools?: string[] }` | `undefined` | Never exposed. Each entry matches a primitive's `id` or its registration key. Takes precedence over `include`. |
740
+ | `serverInfo` | `{ name?: string; version?: string; title?: string; instructions?: string }` | `undefined` | Server identity reported to MCP clients. |
741
+ | `oauth` | `{ resource?: string; requireAudience?: boolean; authorizationServers?: string[]; scopesSupported?: string[] }` | `undefined` | OAuth discovery and token audience settings. See [`server.mcp.oauth`](#servermcpoauth). |
742
+
743
+ ```typescript
744
+ import { Mastra } from '@mastra/core'
745
+
746
+ export const mastra = new Mastra({
747
+ server: {
748
+ mcp: {
749
+ featured: { agents: ['support-agent'] },
750
+ exclude: { tools: ['delete-account'] },
751
+ },
752
+ },
753
+ })
754
+ ```
755
+
756
+ ### server.mcp.oauth
757
+
758
+ **Type:** `object`\
759
+ **Default:** `undefined`
760
+
761
+ OAuth protected-resource metadata for the [built-in MCP server](https://mastra.ai/docs/server/mcp). Used when `server.auth` is configured.
762
+
763
+ | Property | Type | Default | Description |
764
+ | ---------------------- | ---------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
765
+ | `resource` | `string` | Endpoint URL derived from the request | Canonical public URL of the MCP endpoint, for example `https://my-app.example.com/api/mcp`. Setting it also requires the token's `aud` claim to include this URL on `/api/mcp`, for auth providers that support audience checks. |
766
+ | `requireAudience` | `boolean` | `false` | Requires `resource`. Rejects MCP requests with a `401` when the auth provider that accepted the token can't check the audience, including such providers inside `CompositeAuth`. When `false`, those requests are accepted and Mastra logs a warning at startup. |
767
+ | `authorizationServers` | `string[]` | From the auth provider | Issuer URLs of the authorization servers that MCP clients get tokens from. |
768
+ | `scopesSupported` | `string[]` | From the auth provider | OAuth scopes advertised to MCP clients. Left out of the metadata when unset. |
769
+
770
+ ```typescript
771
+ import { Mastra } from '@mastra/core'
772
+ import { MastraJwtAuth } from '@mastra/auth'
773
+
774
+ export const mastra = new Mastra({
775
+ server: {
776
+ auth: new MastraJwtAuth({
777
+ jwksUri: 'https://auth.example.com/.well-known/jwks.json',
778
+ issuer: 'https://auth.example.com/',
779
+ }),
780
+ mcp: {
781
+ oauth: { resource: 'https://my-app.example.com/api/mcp' },
782
+ },
783
+ },
784
+ })
785
+ ```
786
+
723
787
  ### server.mcpOptions
724
788
 
725
789
  **Type:** `object`\
@@ -109,6 +109,7 @@ The resolver also exposes methods for manual control:
109
109
  - `refresh()` fetches from the platform immediately, then updates the cache and returns the tool record. Rejects if the platform fetch fails.
110
110
  - `disconnect()` clears the cached snapshots and closes the MCP transports of the state behind this resolver. Resolvers created with identical options share that state, so this disconnects them too. A later resolution rebuilds the state, and already-returned MCP tools reconnect on their next call.
111
111
  - `with(extra)` returns a new resolver that merges extra tools into every resolution, giving extras priority on key collision. It accepts a static tool record or a function (sync or async) and calls chain. For the same merge using a spread of the resolver's result in a `tools` callback, see [Add tools to an agent](https://mastra.ai/docs/mastra-platform/connect).
112
+ - `codeMode(options)` exposes the tools through [Code Mode](#code-mode).
112
113
 
113
114
  To filter on something other than tool keys, or on data that options can't express, post-process the resolved record in the agent's `tools` function. Create the resolver once, outside the function, so its cache is shared:
114
115
 
@@ -144,6 +145,64 @@ Error handling depends on the cause:
144
145
  - If a background refresh fails while a snapshot is cached, the resolver keeps serving the cached toolsets and warns. It rejects only when nothing was ever cached.
145
146
  - A problem with one provider, such as a connection that needs reauthorization, logs a warning and skips that provider. The other providers' tools still load.
146
147
 
148
+ ## Code Mode
149
+
150
+ `codeMode()` gives the agent the connected tools through [Code Mode](https://mastra.ai/docs/agents/code-mode): the agent writes one TypeScript program that calls the tools as `external_*` functions, instead of calling each tool in its own step. Use it when tasks fan out across many calls or providers, such as listing items in one provider and looking each one up in another.
151
+
152
+ ```typescript
153
+ import { Agent } from '@mastra/core/agent'
154
+ import { LocalSandbox } from '@mastra/core/workspace'
155
+ import { tools } from '@mastra/connect'
156
+
157
+ const code = tools({ providers: ['linear', 'slack'] }).codeMode({ sandbox: new LocalSandbox() })
158
+
159
+ export const opsAgent = new Agent({
160
+ id: 'ops',
161
+ name: 'ops',
162
+ instructions: async ctx => ['You help the team track work.', await code.instructions(ctx)],
163
+ model: 'openai/gpt-6-luna',
164
+ tools: code.tools,
165
+ })
166
+ ```
167
+
168
+ > **Warning:** `LocalSandbox` runs the model-written program as a host `node` process with host privileges. Connected tools return third-party data, such as issue text, that can influence the code the model writes. Use `LocalSandbox` only for trusted or local development. See [how Code Mode works](https://mastra.ai/docs/agents/code-mode) for isolated alternatives.
169
+
170
+ `codeMode()` returns two functions, `tools` and `instructions`. Pass both to the agent. Like the resolver, they resolve the current connections on every request. The functions the program can call change as providers are connected or disconnected. Within one request both use the same resolution, and the instructions never declare a function the program can't call.
171
+
172
+ The method accepts every [`createCodeMode()` option](https://mastra.ai/reference/tools/create-code-mode) except `tools` (`sandbox`, `timeout`, `id`), plus `transport` for a [remote sandbox](https://mastra.ai/docs/agents/code-mode) or [in-process isolation](https://mastra.ai/docs/agents/code-mode), and `toolSearch` for [tool search](#tool-search). Every resolver provides it, including the callback form and resolvers returned by `with()`. Extra tools from `with()` join the program's functions.
173
+
174
+ Some tools stay direct agent tools instead of program functions, because they pause the agent run and a call from inside a program can't:
175
+
176
+ - Tools that need approval through `requireApproval`. The agent still waits for the user to approve each call.
177
+ - The `request_connection` tool, so the connect prompt can still pause the run until the user connects.
178
+
179
+ For [MCP providers](#mcp-providers), a `requireApproval` list keeps **all** of that provider's tools direct, including the ones the list doesn't name. Mastra discovers MCP tools at request time and checks the list on each call, so Code Mode has no way to know in advance which calls need approval and keeps every tool from that provider out of the program. Generated HTTP tools work differently, because only the tools that match the list stay direct.
180
+
181
+ ```typescript
182
+ // Every neon-mcp tool stays direct, not just neon-mcp_run_sql
183
+ const ops = tools({
184
+ providers: { 'neon-mcp': { requireApproval: ['neon-mcp_run_sql'] } },
185
+ }).codeMode({ sandbox })
186
+ ```
187
+
188
+ To let a program call that provider's other tools, remove the gated tools with `disallowTools` instead of gating them. To keep them gated, accept that the agent calls the provider's tools one at a time.
189
+
190
+ When there is nothing to orchestrate, for example when the project has no connections yet, `tools` returns only the direct tools and `instructions` returns an empty string.
191
+
192
+ ### Tool search
193
+
194
+ Declaring every function in the instructions uses context on every request: about 4,000 tokens for Linear alone and over 20,000 for Linear, GitHub, and Stripe together. With tool search, the instructions list only the function names, and the agent gets a `search_functions` tool that returns the TypeScript declarations for the functions it needs. The agent searches by what it wants to do or by exact names from the list, then writes the program. The program can still call every function. Only the declarations move behind the search.
195
+
196
+ Tool search turns on by itself when declaring every function would take more than about 10,000 tokens. Set `toolSearch` to choose:
197
+
198
+ ```typescript
199
+ // Always list names only and search for declarations
200
+ const searching = tools().codeMode({ sandbox: new LocalSandbox(), toolSearch: true })
201
+
202
+ // Always declare every function up front
203
+ const declared = tools().codeMode({ sandbox: new LocalSandbox(), toolSearch: false })
204
+ ```
205
+
147
206
  ## Choosing providers
148
207
 
149
208
  The `providers` array form is an allowlist: only listed providers are returned. Without the option, every connected provider with a supported toolset is included. A listed provider with no connection in the project yet is skipped and included automatically once a connection is attached. In the record form, `false` excludes a provider and never errors, even for IDs that match nothing.
@@ -38,7 +38,7 @@ export const mastra = new Mastra({
38
38
 
39
39
  **builder** (`AgentBuilderOptions`): Agent Builder configuration. See the AgentBuilderOptions reference. Omit or set enabled: false to disable the Builder.
40
40
 
41
- **source** (`'code' | 'db'`): Where agent overrides are stored. With 'db', overrides live in the configured storage backend and Studio shows the save and publish flow. With 'code', overrides live as per-agent JSON files on disk (routed through a local FilesystemStore) and Studio shows filesystem actions. See Editor storage options for the difference. (Default: `'db'`)
41
+ **source** (`'code' | 'db'`): Where agent overrides are stored. With 'db', overrides live in the configured storage backend and Studio shows the save and publish flow. With 'code', overrides live as per-agent JSON files at codePath (routed through a local FilesystemStore) and Studio shows filesystem actions. When source is 'code' and a source-control provider is configured, agent overrides are persisted through source-control operations instead of the local filesystem, and the provider controls the repository path. A provider passed as sourceControlProvider uses its own pathPrefix; the provider created from environment variables uses MASTRA_SOURCE_STORAGE_PATH_PREFIX when it is set, and codePath otherwise. The environment provider is created only when MASTRA_SOURCE_PROVIDER is github, an endpoint is set (MASTRA_SOURCE_PROVIDER_ENDPOINT, MASTRA_SHARED_API_URL, or MASTRA_CLOUD_API_ENDPOINT), and a token is set (MASTRA_PLATFORM_ACCESS_TOKEN or MASTRA_CLOUD_ACCESS_TOKEN). Each list is checked in order and the first defined variable wins, so an empty higher-priority variable disables the provider instead of falling back. The endpoint is a Mastra platform API that brokers the GitHub operations, so the provider never calls the GitHub API directly. Without a provider, overrides stay in the local files at codePath. See Editor storage options for the difference. (Default: `'db'`)
42
42
 
43
43
  **codePath** (`string`): Directory used by the 'code' source for per-agent JSON files. Ignored when source is not 'code'. (Default: `'./mastra/editor'`)
44
44
 
@@ -329,7 +329,9 @@ The Reference section provides documentation of Mastra's API, including paramete
329
329
  - [Vector Databases](https://mastra.ai/reference/rag/vector-databases)
330
330
  - [.chunk()](https://mastra.ai/reference/rag/chunk)
331
331
  - [Overview](https://mastra.ai/reference/schedules/overview)
332
+ - [Built-in MCP tools](https://mastra.ai/reference/server/builtin-mcp-tools)
332
333
  - [createRoute()](https://mastra.ai/reference/server/create-route)
334
+ - [dispatchRoute()](https://mastra.ai/reference/server/dispatch-route)
333
335
  - [Elysia Adapter](https://mastra.ai/reference/server/elysia-adapter)
334
336
  - [Express Adapter](https://mastra.ai/reference/server/express-adapter)
335
337
  - [Fastify Adapter](https://mastra.ai/reference/server/fastify-adapter)
@@ -96,7 +96,7 @@ explainAccess(
96
96
  ): Promise<KnowledgeAccessExplanation>
97
97
  ```
98
98
 
99
- Explains why a run holding `runScopes` can or can't reach a scope or page. `runScopes` are raw run scopes, as you'd pass to an agent. `target.page` takes a page ID or a page path such as `org:acme#policies/refund`.
99
+ Explains why a run holding `runScopes` can or can't reach a scope or page. `runScopes` are canonical addresses, including `resource:` and `thread:` (`resource:slack%3AU123` for Memory resource `slack:U123`). `target.page` takes a page ID or a page path such as `org:acme#policies/refund`.
100
100
 
101
101
  ```typescript
102
102
  await knowledge.explainAccess(['org:acme'], { page: 'team:acme:support#refunds' })
@@ -55,9 +55,9 @@ knowledgeMemoryScopes({ org: 'workspace:$workspaceId', orgRole: 'contributor' })
55
55
  knowledgeScopeAddress(pattern: string, params: Record<string, string>): string
56
56
  ```
57
57
 
58
- Builds a canonical scope address from a pattern and raw parameter values. Use it in host code for Knowledge APIs, `pinnedContext` entries and page references.
58
+ Builds a canonical scope address from a pattern and raw parameter values. Use it in host code for agent scopes, Knowledge APIs, `pinnedContext` entries and page references.
59
59
 
60
- Inside values, `%`, `/` and `#` are encoded as `%25`, `%2F` and `%23`. `:` is encoded as `%3A` in every parameter except the last. It throws when a parameter is missing or empty.
60
+ Inside every value, `%`, `/`, `#` and `:` are encoded as `%25`, `%2F`, `%23` and `%3A`. Each value fills exactly one segment. It throws when a parameter is missing or empty.
61
61
 
62
62
  ```typescript
63
63
  import { knowledgeScopeAddress } from '@mastra/core/knowledge'
@@ -66,10 +66,50 @@ knowledgeScopeAddress('resource:$resourceId', { resourceId: 'acme/dana' })
66
66
  // 'resource:acme%2Fdana'
67
67
 
68
68
  knowledgeScopeAddress('team:$orgId:$teamId', { orgId: 'a:b', teamId: 'c:d' })
69
- // 'team:a%3Ab:c:d'
69
+ // 'team:a%3Ab:c%3Ad'
70
70
  ```
71
71
 
72
- > **Note:** Don't pass the result as an agent scope. Agent scopes take raw IDs (`resource:acme/dana`), and Knowledge encodes them at run start. See [set a run's scopes](https://mastra.ai/docs/knowledge/scopes-and-access).
72
+ ## `encodeKnowledgeScopeId()`
73
+
74
+ ```typescript
75
+ encodeKnowledgeScopeId(id: string): string
76
+ ```
77
+
78
+ Encodes one ID, such as a tenant or user ID, for one segment of a scope address. It applies the same encoding as `knowledgeScopeAddress()`. Use it when you build an address with a template string:
79
+
80
+ ```typescript
81
+ import { encodeKnowledgeScopeId } from '@mastra/core/knowledge'
82
+
83
+ const scope = `org:${encodeKnowledgeScopeId('auth0|a:b')}`
84
+ // 'org:auth0|a%3Ab'
85
+ ```
86
+
87
+ ## `decodeKnowledgeScopeId()`
88
+
89
+ ```typescript
90
+ decodeKnowledgeScopeId(segment: string): string | null
91
+ ```
92
+
93
+ Returns the ID in one segment of a scope address. It returns `null` when the segment isn't canonically encoded, for example when it holds a raw `:` or a lowercase escape such as `%3a`.
94
+
95
+ ```typescript
96
+ import { decodeKnowledgeScopeId } from '@mastra/core/knowledge'
97
+
98
+ decodeKnowledgeScopeId('slack%3AU123') // 'slack:U123'
99
+ decodeKnowledgeScopeId('a:b') // null
100
+ ```
101
+
102
+ ## Agent scopes
103
+
104
+ Agent scopes are canonical addresses. Encode any ID that contains `:`, `/`, `#` or `%`, with `encodeKnowledgeScopeId()` or `knowledgeScopeAddress()`. A raw ID, such as `org:a:b` for org `a:b`, fails at run start:
105
+
106
+ ```text
107
+ Knowledge run scope "org:a:b" does not match a declared scope type. Declare it in Knowledge `scopes` (for Memory's resource:/thread: scopes, spread `...knowledgeMemoryScopes()`), and encode ids containing ":", "/", "#" or "%" with encodeKnowledgeScopeId.
108
+ ```
109
+
110
+ `resource:` and `thread:` agent scopes are the exception. They set the run's Memory resource and thread, so they take Memory's raw IDs, and Knowledge encodes them. A run with Memory resource `slack:U123` holds `resource:slack%3AU123`. See [set a run's scopes](https://mastra.ai/docs/knowledge/scopes-and-access).
111
+
112
+ Scopes stored by earlier alpha releases with a raw `:` in their last segment aren't moved to the encoded address. See [Patterns and params](https://mastra.ai/reference/knowledge/scope-declarations).
73
113
 
74
114
  ## Related
75
115
 
@@ -56,9 +56,13 @@ export const knowledge = new Knowledge({
56
56
 
57
57
  A key such as `team:$orgId:$teamId` is a pattern. The text before the first `:` is the type, and each `$name` segment is a param. The address `team:acme:support` matches it with `$orgId = acme` and `$teamId = support`.
58
58
 
59
- The last param takes the rest of the value, so `resource:$resourceId` matches `resource:user:123` with `$resourceId = user:123`. Memory ids that contain `:` keep working.
59
+ Each param matches exactly one segment, so an address has as many segments as its pattern. `resource:user:123` doesn't match `resource:$resourceId`. An ID that contains `:`, `/`, `#` or `%` is encoded into one segment, so user `user:123` is `resource:user%3A123`. Build addresses with [`encodeKnowledgeScopeId()` or `knowledgeScopeAddress()`](https://mastra.ai/reference/knowledge/knowledge-memory-scopes). Memory IDs are encoded for you.
60
60
 
61
- A type can have several patterns only when no address can match two of them. Each pair must have different literal text at the same position:
61
+ > **Scopes stored by earlier alpha releases:** Earlier releases let the last param take the rest of the address, raw colons included. A scope stored that way, such as `resource:slack:U123` for Memory resource `slack:U123`, now has a new address, `resource:slack%3AU123`. Runs reach the new, empty scope. Pages, pins and notes under the old address stay in storage, but runs with that Memory resource no longer reach them, and Knowledge doesn't move them.
62
+ >
63
+ > A stored scope whose address now matches a different pattern, such as `org:acme:viewer` stored as an `org:$orgId` scope before you declared `org:$orgId:viewer`, gets no rules from the new pattern. Using it as a scope of the new pattern throws.
64
+
65
+ A type can have several patterns only when no address can match two of them. Patterns with different numbers of segments never overlap. Patterns with the same number must have different literal text at the same position:
62
66
 
63
67
  ```typescript
64
68
  scopes: {
@@ -73,7 +77,7 @@ Overlapping patterns fail at startup. There's no precedence between them:
73
77
  Knowledge scope patterns "role:$orgId:$role" and "role:$orgId:admin" overlap; patterns of a type must be pairwise disjoint.
74
78
  ```
75
79
 
76
- A pattern ending in a param overlaps a longer one with the same start, so `kb:$orgId` and `kb:$orgId:public` overlap too. Use two types, such as `kb-public:$orgId` and `kb-internal:$orgId`.
80
+ `kb:$orgId` and `kb:$orgId:public` can be declared together, because `kb:acme` and `kb:acme:public` have different numbers of segments. Each is its own scope with its own rules. Holding `kb:acme` gives no role on `kb:acme:public` unless a rule on `kb:$orgId:public` names `kb:$orgId`.
77
81
 
78
82
  ## Rules
79
83