@mastra/mcp-docs-server 0.13.7-alpha.1 → 0.13.7-alpha.3
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.
- package/.docs/organized/changelogs/%40mastra%2Fclient-js.md +37 -37
- package/.docs/organized/changelogs/%40mastra%2Fcloudflare-d1.md +18 -18
- package/.docs/organized/changelogs/%40mastra%2Fcloudflare.md +18 -18
- package/.docs/organized/changelogs/%40mastra%2Fcore.md +39 -39
- package/.docs/organized/changelogs/%40mastra%2Fdeployer-cloudflare.md +21 -21
- package/.docs/organized/changelogs/%40mastra%2Fdeployer.md +42 -42
- package/.docs/organized/changelogs/%40mastra%2Flibsql.md +29 -29
- package/.docs/organized/changelogs/%40mastra%2Fmcp-docs-server.md +22 -22
- package/.docs/organized/changelogs/%40mastra%2Fmemory.md +29 -29
- package/.docs/organized/changelogs/%40mastra%2Fmongodb.md +20 -20
- package/.docs/organized/changelogs/%40mastra%2Fmssql.md +17 -0
- package/.docs/organized/changelogs/%40mastra%2Fpg.md +29 -29
- package/.docs/organized/changelogs/%40mastra%2Fserver.md +36 -36
- package/.docs/organized/changelogs/%40mastra%2Fupstash.md +29 -29
- package/.docs/organized/changelogs/%40mastra%2Fvectorize.md +18 -18
- package/.docs/organized/changelogs/%40mastra%2Fvoice-cloudflare.md +18 -18
- package/.docs/organized/changelogs/mastra.md +21 -21
- package/.docs/organized/code-examples/agent.md +93 -3
- package/.docs/organized/code-examples/ai-sdk-v5.md +4 -4
- package/.docs/raw/agents/input-processors.mdx +268 -0
- package/.docs/raw/agents/using-tools-and-mcp.mdx +39 -0
- package/.docs/raw/community/contributing-templates.mdx +2 -2
- package/.docs/raw/observability/tracing.mdx +44 -0
- package/.docs/raw/reference/agents/agent.mdx +7 -0
- package/.docs/raw/reference/cli/dev.mdx +6 -0
- package/.docs/raw/reference/client-js/memory.mdx +18 -0
- package/.docs/raw/reference/memory/Memory.mdx +1 -0
- package/.docs/raw/reference/memory/deleteMessages.mdx +95 -0
- package/.docs/raw/reference/memory/getThreadsByResourceId.mdx +33 -1
- package/.docs/raw/reference/rag/upstash.mdx +112 -5
- package/.docs/raw/reference/scorers/answer-relevancy.mdx +0 -1
- package/.docs/raw/reference/scorers/faithfulness.mdx +0 -1
- package/.docs/raw/reference/scorers/hallucination.mdx +0 -2
- package/.docs/raw/reference/scorers/llm-scorer.mdx +45 -1
- package/.docs/raw/reference/storage/libsql.mdx +7 -4
- package/.docs/raw/reference/storage/mssql.mdx +7 -3
- package/.docs/raw/reference/storage/postgresql.mdx +7 -3
- package/.docs/raw/reference/templates.mdx +11 -5
- package/.docs/raw/scorers/custom-scorers.mdx +319 -0
- package/.docs/raw/scorers/off-the-shelf-scorers.mdx +30 -0
- package/.docs/raw/scorers/overview.mdx +124 -0
- package/package.json +6 -6
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Input Processors"
|
|
3
|
+
description: "Learn how to use input processors to intercept and modify agent messages before they reach the language model."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Input Processors
|
|
7
|
+
|
|
8
|
+
Input Processors allow you to intercept, modify, validate, or filter messages _before_ they are sent to the language model. This is useful for implementing guardrails, content moderation, message transformation, and security controls.
|
|
9
|
+
|
|
10
|
+
Processors operate on the messages in your conversation thread. They can modify, filter, or validate content, and even abort the request entirely if certain conditions are met.
|
|
11
|
+
|
|
12
|
+
## Built-in Processors
|
|
13
|
+
|
|
14
|
+
Mastra provides several built-in processors for common use cases:
|
|
15
|
+
|
|
16
|
+
### `UnicodeNormalizer`
|
|
17
|
+
|
|
18
|
+
This processor normalizes Unicode text to ensure consistent formatting and remove potentially problematic characters.
|
|
19
|
+
|
|
20
|
+
```typescript copy showLineNumbers {9-11}
|
|
21
|
+
import { Agent } from "@mastra/core/agent";
|
|
22
|
+
import { UnicodeNormalizer } from "@mastra/core/agent/input-processor/processors";
|
|
23
|
+
import { openai } from "@ai-sdk/openai";
|
|
24
|
+
|
|
25
|
+
const agent = new Agent({
|
|
26
|
+
name: 'normalized-agent',
|
|
27
|
+
instructions: 'You are a helpful assistant',
|
|
28
|
+
model: openai("gpt-4o"),
|
|
29
|
+
inputProcessors: [
|
|
30
|
+
new UnicodeNormalizer({
|
|
31
|
+
stripControlChars: true,
|
|
32
|
+
collapseWhitespace: true,
|
|
33
|
+
}),
|
|
34
|
+
],
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Available options:
|
|
39
|
+
- `stripControlChars`: Remove control characters (default: false)
|
|
40
|
+
- `preserveEmojis`: Keep emojis intact (default: true)
|
|
41
|
+
- `collapseWhitespace`: Collapse multiple spaces/newlines (default: true)
|
|
42
|
+
- `trim`: Remove leading/trailing whitespace (default: true)
|
|
43
|
+
|
|
44
|
+
### `ModerationInputProcessor`
|
|
45
|
+
|
|
46
|
+
This processor provides content moderation using an LLM to detect inappropriate content across multiple categories.
|
|
47
|
+
|
|
48
|
+
```typescript copy showLineNumbers {5-13}
|
|
49
|
+
import { ModerationInputProcessor } from "@mastra/core/agent/input-processor/processors";
|
|
50
|
+
|
|
51
|
+
const agent = new Agent({
|
|
52
|
+
inputProcessors: [
|
|
53
|
+
new ModerationInputProcessor({
|
|
54
|
+
model: openai("gpt-4.1-nano"), // Use a fast, cost-effective model
|
|
55
|
+
threshold: 0.7, // Confidence threshold for flagging
|
|
56
|
+
strategy: 'block', // Block flagged content
|
|
57
|
+
categories: ['hate', 'harassment', 'violence'], // Custom categories
|
|
58
|
+
}),
|
|
59
|
+
],
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Available options:
|
|
64
|
+
- `model`: Language model for moderation analysis (required)
|
|
65
|
+
- `categories`: Array of categories to check (default: ['hate','hate/threatening','harassment','harassment/threatening','self-harm','self-harm/intent','self-harm/instructions','sexual','sexual/minors','violence','violence/graphic'])
|
|
66
|
+
- `threshold`: Confidence threshold for flagging (0-1, default: 0.5)
|
|
67
|
+
- `strategy`: Action when content is flagged (default: 'block')
|
|
68
|
+
- `customInstructions`: Custom instructions for the moderation agent
|
|
69
|
+
|
|
70
|
+
Strategies available:
|
|
71
|
+
- `block`: Reject the request with an error (default)
|
|
72
|
+
- `warn`: Log warning but allow content through
|
|
73
|
+
- `filter`: Remove flagged messages but continue processing
|
|
74
|
+
|
|
75
|
+
### `PromptInjectionDetector`
|
|
76
|
+
|
|
77
|
+
This processor detects and prevents prompt injection attacks, jailbreaks, and system manipulation attempts.
|
|
78
|
+
|
|
79
|
+
```typescript copy showLineNumbers {5-12}
|
|
80
|
+
import { PromptInjectionDetector } from "@mastra/core/agent/input-processor/processors";
|
|
81
|
+
|
|
82
|
+
const agent = new Agent({
|
|
83
|
+
inputProcessors: [
|
|
84
|
+
new PromptInjectionDetector({
|
|
85
|
+
model: openai("gpt-4.1-nano"),
|
|
86
|
+
threshold: 0.8, // Higher threshold for fewer false positives
|
|
87
|
+
strategy: 'rewrite', // Attempt to neutralize while preserving intent
|
|
88
|
+
detectionTypes: ['injection', 'jailbreak', 'system-override'],
|
|
89
|
+
}),
|
|
90
|
+
],
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Available options:
|
|
95
|
+
- `model`: Language model for injection detection (required)
|
|
96
|
+
- `detectionTypes`: Array of injection types to detect (default: ['injection', 'jailbreak', 'system-override'])
|
|
97
|
+
- `threshold`: Confidence threshold for flagging (0-1, default: 0.7)
|
|
98
|
+
- `strategy`: Action when injection is detected (default: 'block')
|
|
99
|
+
- `instructions`: Custom detection instructions for the agent
|
|
100
|
+
- `includeScores`: Whether to include confidence scores in logs (default: false)
|
|
101
|
+
|
|
102
|
+
Strategies available:
|
|
103
|
+
- `block`: Reject the request (default)
|
|
104
|
+
- `warn`: Log warning but allow through
|
|
105
|
+
- `filter`: Remove flagged messages
|
|
106
|
+
- `rewrite`: Attempt to neutralize the injection while preserving legitimate intent
|
|
107
|
+
|
|
108
|
+
### `PIIDetector`
|
|
109
|
+
|
|
110
|
+
This processor detects and optionally redacts personally identifiable information (PII) from messages.
|
|
111
|
+
|
|
112
|
+
```typescript copy showLineNumbers {5-14}
|
|
113
|
+
import { PIIDetector } from "@mastra/core/agent/input-processor/processors";
|
|
114
|
+
|
|
115
|
+
const agent = new Agent({
|
|
116
|
+
inputProcessors: [
|
|
117
|
+
new PIIDetector({
|
|
118
|
+
model: openai("gpt-4.1-nano"),
|
|
119
|
+
threshold: 0.6,
|
|
120
|
+
strategy: 'redact', // Automatically redact detected PII
|
|
121
|
+
detectionTypes: ['email', 'phone', 'credit-card', 'ssn', 'api-key', 'crypto-wallet', 'iban'],
|
|
122
|
+
redactionMethod: 'mask', // Preserve format while masking
|
|
123
|
+
preserveFormat: true, // Keep original structure in redacted values
|
|
124
|
+
includeDetections: true, // Log details for compliance auditing
|
|
125
|
+
}),
|
|
126
|
+
],
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Available options:
|
|
131
|
+
- `model`: Language model for PII detection (required)
|
|
132
|
+
- `detectionTypes`: Array of PII types to detect (default: ['email', 'phone', 'credit-card', 'ssn', 'api-key', 'ip-address', 'name', 'address', 'date-of-birth', 'url', 'uuid', 'crypto-wallet', 'iban'])
|
|
133
|
+
- `threshold`: Confidence threshold for flagging (0-1, default: 0.6)
|
|
134
|
+
- `strategy`: Action when PII is detected (default: 'block')
|
|
135
|
+
- `redactionMethod`: How to redact PII ('mask', 'hash', 'remove', 'placeholder', default: 'mask')
|
|
136
|
+
- `preserveFormat`: Maintain PII structure during redaction (default: true)
|
|
137
|
+
- `includeDetections`: Include detection details in logs for compliance (default: false)
|
|
138
|
+
- `instructions`: Custom detection instructions for the agent
|
|
139
|
+
|
|
140
|
+
Strategies available:
|
|
141
|
+
- `block`: Reject requests containing PII (default)
|
|
142
|
+
- `warn`: Log warning but allow through
|
|
143
|
+
- `filter`: Remove messages containing PII
|
|
144
|
+
- `redact`: Replace PII with placeholder values
|
|
145
|
+
|
|
146
|
+
### `LanguageDetector`
|
|
147
|
+
|
|
148
|
+
This processor detects the language of incoming messages and can automatically translate them to a target language.
|
|
149
|
+
|
|
150
|
+
```typescript copy showLineNumbers {5-12}
|
|
151
|
+
import { LanguageDetector } from "@mastra/core/agent/input-processor/processors";
|
|
152
|
+
|
|
153
|
+
const agent = new Agent({
|
|
154
|
+
inputProcessors: [
|
|
155
|
+
new LanguageDetector({
|
|
156
|
+
model: openai("gpt-4o"),
|
|
157
|
+
targetLanguages: ['English', 'en'], // Accept English content
|
|
158
|
+
strategy: 'translate', // Auto-translate non-English content
|
|
159
|
+
threshold: 0.8, // High confidence threshold
|
|
160
|
+
}),
|
|
161
|
+
],
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Available options:
|
|
166
|
+
- `model`: Language model for detection and translation (required)
|
|
167
|
+
- `targetLanguages`: Array of target languages (language names or ISO codes)
|
|
168
|
+
- `threshold`: Confidence threshold for language detection (0-1, default: 0.7)
|
|
169
|
+
- `strategy`: Action when non-target language is detected (default: 'detect')
|
|
170
|
+
- `preserveOriginal`: Keep original content in metadata (default: true)
|
|
171
|
+
- `instructions`: Custom detection instructions for the agent
|
|
172
|
+
|
|
173
|
+
Strategies available:
|
|
174
|
+
- `detect`: Only detect language, don't translate (default)
|
|
175
|
+
- `translate`: Automatically translate to target language
|
|
176
|
+
- `block`: Reject content not in target language
|
|
177
|
+
- `warn`: Log warning but allow content through
|
|
178
|
+
|
|
179
|
+
## Applying Multiple Processors
|
|
180
|
+
|
|
181
|
+
You can chain multiple processors. They execute sequentially in the order they appear in the `inputProcessors` array. The output of one processor becomes the input for the next.
|
|
182
|
+
|
|
183
|
+
**Order matters!** Generally, it's best practice to place text normalization first, security checks next, and content modification last.
|
|
184
|
+
|
|
185
|
+
```typescript copy showLineNumbers {9-18}
|
|
186
|
+
import { Agent } from "@mastra/core/agent";
|
|
187
|
+
import {
|
|
188
|
+
UnicodeNormalizer,
|
|
189
|
+
ModerationInputProcessor,
|
|
190
|
+
PromptInjectionDetector,
|
|
191
|
+
PIIDetector
|
|
192
|
+
} from "@mastra/core/agent/input-processor/processors";
|
|
193
|
+
|
|
194
|
+
const secureAgent = new Agent({
|
|
195
|
+
inputProcessors: [
|
|
196
|
+
// 1. Normalize text first
|
|
197
|
+
new UnicodeNormalizer({ stripControlChars: true }),
|
|
198
|
+
// 2. Check for security threats
|
|
199
|
+
new PromptInjectionDetector({ model: openai("gpt-4.1-nano") }),
|
|
200
|
+
// 3. Moderate content
|
|
201
|
+
new ModerationInputProcessor({ model: openai("gpt-4.1-nano") }),
|
|
202
|
+
// 4. Handle PII last
|
|
203
|
+
new PIIDetector({ model: openai("gpt-4.1-nano"), strategy: 'redact' }),
|
|
204
|
+
],
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Creating Custom Processors
|
|
209
|
+
|
|
210
|
+
You can create custom processors by implementing the `InputProcessor` interface.
|
|
211
|
+
|
|
212
|
+
```typescript copy showLineNumbers {4-19,23-26}
|
|
213
|
+
import type { InputProcessor, MastraMessageV2 } from "@mastra/core/agent";
|
|
214
|
+
|
|
215
|
+
class MessageLengthLimiter implements InputProcessor {
|
|
216
|
+
readonly name = 'message-length-limiter';
|
|
217
|
+
|
|
218
|
+
constructor(private maxLength: number = 1000) {}
|
|
219
|
+
|
|
220
|
+
process({ messages, abort }: {
|
|
221
|
+
messages: MastraMessageV2[];
|
|
222
|
+
abort: (reason?: string) => never
|
|
223
|
+
}): MastraMessageV2[] {
|
|
224
|
+
// Check total message length
|
|
225
|
+
const totalLength = messages.reduce((sum, msg) => {
|
|
226
|
+
return sum + msg.content.parts
|
|
227
|
+
.filter(part => part.type === 'text')
|
|
228
|
+
.reduce((partSum, part) => partSum + (part as any).text.length, 0);
|
|
229
|
+
}, 0);
|
|
230
|
+
|
|
231
|
+
if (totalLength > this.maxLength) {
|
|
232
|
+
abort(`Message too long: ${totalLength} characters (max: ${this.maxLength})`);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return messages;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Use the custom processor
|
|
240
|
+
const agent = new Agent({
|
|
241
|
+
inputProcessors: [
|
|
242
|
+
new MessageLengthLimiter(2000), // Limit to 2000 characters
|
|
243
|
+
],
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
When creating custom processors:
|
|
248
|
+
- Always return the `messages` array (potentially modified)
|
|
249
|
+
- Use `abort(reason)` to terminate processing early
|
|
250
|
+
- Mutate the input messages directly
|
|
251
|
+
- Keep processors focused on a single responsibility
|
|
252
|
+
|
|
253
|
+
## Integration with Agent Methods
|
|
254
|
+
|
|
255
|
+
Input processors work with both `generate()` and `stream()` methods. The entire processor pipeline completes before the agent begins generating or streaming a response.
|
|
256
|
+
|
|
257
|
+
```typescript copy showLineNumbers
|
|
258
|
+
// Processors run before generate()
|
|
259
|
+
const result = await agent.generate('Hello');
|
|
260
|
+
|
|
261
|
+
// Processors also run before stream()
|
|
262
|
+
const stream = await agent.stream('Hello');
|
|
263
|
+
for await (const chunk of stream.textStream) {
|
|
264
|
+
console.log(chunk);
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
If any processor calls `abort()`, the request terminates immediately and subsequent processors are not executed. The agent returns an error response with details about why the request was blocked.
|
|
@@ -7,6 +7,10 @@ description: Learn how to create tools, add them to Mastra agents, and integrate
|
|
|
7
7
|
|
|
8
8
|
Tools are typed functions that can be executed by agents or workflows. Each tool has a schema defining its inputs, an executor function implementing its logic, and optional access to configured integrations.
|
|
9
9
|
|
|
10
|
+
Mastra supports two patterns for providing tools to agents:
|
|
11
|
+
- **Direct assignment**: Static tools available at initialization
|
|
12
|
+
- **Function-based**: Dynamic tools resolved based on runtime context
|
|
13
|
+
|
|
10
14
|
## Creating Tools
|
|
11
15
|
|
|
12
16
|
Here's a basic example of creating a tool:
|
|
@@ -107,6 +111,41 @@ const agent = new Agent({
|
|
|
107
111
|
});
|
|
108
112
|
```
|
|
109
113
|
|
|
114
|
+
When creating agents that will consume an MCP server in the same repo they need to connect to, always use function based tools to prevent race conditions.
|
|
115
|
+
|
|
116
|
+
```typescript filename="src/mastra/agents/selfReferencingAgent.ts"
|
|
117
|
+
import { Agent } from "@mastra/core/agent";
|
|
118
|
+
import { MCPServer } from "@mastra/mcp";
|
|
119
|
+
import { MCPClient } from "@mastra/mcp";
|
|
120
|
+
import { openai } from "@ai-sdk/openai";
|
|
121
|
+
|
|
122
|
+
const myAgent = new Agent({
|
|
123
|
+
name: "My Agent",
|
|
124
|
+
description: "An agent that can use tools from an http MCP server",
|
|
125
|
+
instructions: "You can use remote calculation tools.",
|
|
126
|
+
model: openai("gpt-4o-mini"),
|
|
127
|
+
tools: async () => {
|
|
128
|
+
// Tools resolve when needed, not during initialization
|
|
129
|
+
const mcpClient = new MCPClient({
|
|
130
|
+
servers: {
|
|
131
|
+
myServer: {
|
|
132
|
+
url: new URL("http://localhost:4111/api/mcp/mcpServer/mcp"),
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
return await mcpClient.getTools();
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// This works because tools resolve after server startup
|
|
141
|
+
export const mcpServer = new MCPServer({
|
|
142
|
+
name: "My MCP Server",
|
|
143
|
+
agents: {
|
|
144
|
+
myAgent
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
110
149
|
For more details on configuring `MCPClient` and the difference between static and dynamic MCP server configurations, see the [MCP Overview](/docs/tools-mcp/mcp-overview).
|
|
111
150
|
|
|
112
151
|
## Accessing MCP Resources
|
|
@@ -68,7 +68,7 @@ Ensure your template meets all requirements outlined in the [Templates Reference
|
|
|
68
68
|
|
|
69
69
|
Submit your template using our contribution form:
|
|
70
70
|
|
|
71
|
-
**[Submit Template Contribution](https://
|
|
71
|
+
**[Submit Template Contribution](https://docs.google.com/forms/d/e/1FAIpQLSfiqD4oeOVaqoE3t10KZJw4QM3fxAQPIOcZBqUYkewJIsQKFw/viewform)**
|
|
72
72
|
|
|
73
73
|
### Required Information
|
|
74
74
|
|
|
@@ -189,4 +189,4 @@ Ready to contribute a template?
|
|
|
189
189
|
|
|
190
190
|
<Callout type="info">
|
|
191
191
|
Your contributions help grow the Mastra ecosystem and provide valuable resources for the entire community. We look forward to seeing your innovative templates!
|
|
192
|
-
</Callout>
|
|
192
|
+
</Callout>
|
|
@@ -135,6 +135,50 @@ sdk.start();
|
|
|
135
135
|
|
|
136
136
|
When Mastra finds a custom instrumentation file, it automatically replaces the default instrumentation and bundles it during the build process.
|
|
137
137
|
|
|
138
|
+
### Tracing Outside Mastra Server Environment
|
|
139
|
+
|
|
140
|
+
When using `mastra start` or `mastra dev` commands, Mastra automatically provisions and loads the necessary instrumentation files for tracing. However, when using Mastra as a dependency in your own application (outside the Mastra server environment), you'll need to manually provide the instrumentation file.
|
|
141
|
+
|
|
142
|
+
To enable tracing in this case:
|
|
143
|
+
|
|
144
|
+
1. Enable Mastra telemetry in your configuration:
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
export const mastra = new Mastra({
|
|
148
|
+
telemetry: {
|
|
149
|
+
enabled: true,
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
2. Create an instrumentation file in your project (e.g., `instrumentation.mjs`):
|
|
155
|
+
|
|
156
|
+
```typescript
|
|
157
|
+
import { NodeSDK } from '@opentelemetry/sdk-node';
|
|
158
|
+
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
|
|
159
|
+
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
|
|
160
|
+
|
|
161
|
+
const sdk = new NodeSDK({
|
|
162
|
+
traceExporter: new OTLPTraceExporter(),
|
|
163
|
+
instrumentations: [getNodeAutoInstrumentations()],
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
sdk.start();
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
3. Add OpenTelemetry environment variables:
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
OTEL_EXPORTER_OTLP_ENDPOINT=https://api.braintrust.dev/otel
|
|
173
|
+
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer <Your API Key>, x-bt-parent=project_name:<Your Project Name>"
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
4. Run the OpenTelemetry SDK before your application:
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
node --import=./instrumentation.mjs --import=@opentelemetry/instrumentation/hook.mjs src/index.js
|
|
180
|
+
```
|
|
181
|
+
|
|
138
182
|
### Next.js-specific Tracing steps
|
|
139
183
|
|
|
140
184
|
If you're using Next.js, you have three additional configuration steps:
|
|
@@ -61,6 +61,13 @@ constructor(config: AgentConfig<TAgentId, TTools, TMetrics>)
|
|
|
61
61
|
description:
|
|
62
62
|
"Tools that the agent can use. Can be a static object or a function that returns tools.",
|
|
63
63
|
},
|
|
64
|
+
{
|
|
65
|
+
name: "inputProcessors",
|
|
66
|
+
type: "InputProcessor[] | ({ runtimeContext: RuntimeContext }) => InputProcessor[] | Promise<InputProcessor[]>",
|
|
67
|
+
isOptional: true,
|
|
68
|
+
description:
|
|
69
|
+
"Input processors that run sequentially before messages are sent to the language model. These middleware components can intercept, modify, validate, or filter messages. Each processor receives an array of MastraMessageV2 objects and an abort function for early termination. Can be a static array or a function that returns processors based on runtime context.",
|
|
70
|
+
},
|
|
64
71
|
{
|
|
65
72
|
name: "defaultGenerateOptions",
|
|
66
73
|
type: "AgentGenerateOptions",
|
|
@@ -60,6 +60,12 @@ mastra dev [options]
|
|
|
60
60
|
description: "Start the dev server in inspect mode and break at the beginning of the script (cannot be used with --inspect)",
|
|
61
61
|
isOptional: true,
|
|
62
62
|
},
|
|
63
|
+
{
|
|
64
|
+
name: "--custom-args",
|
|
65
|
+
type: "string",
|
|
66
|
+
description: "Comma-separated list of custom arguments to pass to the dev server. IE: --experimental-transform-types",
|
|
67
|
+
isOptional: true,
|
|
68
|
+
},
|
|
63
69
|
{
|
|
64
70
|
name: "--help",
|
|
65
71
|
type: "boolean",
|
|
@@ -103,6 +103,24 @@ const { messages } = await thread.getMessages();
|
|
|
103
103
|
const { messages } = await thread.getMessages({ limit: 10 });
|
|
104
104
|
```
|
|
105
105
|
|
|
106
|
+
### Delete a Message
|
|
107
|
+
|
|
108
|
+
Delete a specific message from a thread:
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
const result = await thread.deleteMessage("message-id");
|
|
112
|
+
// Returns: { success: true, message: "Message deleted successfully" }
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Delete Multiple Messages
|
|
116
|
+
|
|
117
|
+
Delete multiple messages from a thread in a single operation:
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
const result = await thread.deleteMessages(["message-1", "message-2", "message-3"]);
|
|
121
|
+
// Returns: { success: true, message: "3 messages deleted successfully" }
|
|
122
|
+
```
|
|
123
|
+
|
|
106
124
|
### Get Memory Status
|
|
107
125
|
|
|
108
126
|
Check the status of the memory system:
|
|
@@ -310,3 +310,4 @@ Mastra supports many embedding models through the [Vercel AI SDK](https://sdk.ve
|
|
|
310
310
|
- [query](/reference/memory/query.mdx)
|
|
311
311
|
- [getThreadById](/reference/memory/getThreadById.mdx)
|
|
312
312
|
- [getThreadsByResourceId](/reference/memory/getThreadsByResourceId.mdx)
|
|
313
|
+
- [deleteMessages](/reference/memory/deleteMessages.mdx)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
---
|
|
2
|
+
section: Memory
|
|
3
|
+
title: deleteMessages
|
|
4
|
+
slug: reference/memory/deleteMessages
|
|
5
|
+
categorySlug: reference
|
|
6
|
+
layout: guide
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# `deleteMessages`
|
|
10
|
+
|
|
11
|
+
Deletes one or more messages from the memory storage. This method accepts arrays to delete multiple messages in a single operation.
|
|
12
|
+
|
|
13
|
+
## Syntax
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
memory.deleteMessages(input: MessageDeleteInput): Promise<void>
|
|
17
|
+
|
|
18
|
+
type MessageDeleteInput =
|
|
19
|
+
| string[] // Array of message IDs
|
|
20
|
+
| { id: string }[] // Array of message objects
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Parameters
|
|
24
|
+
|
|
25
|
+
- `input` (required): An array of messages to delete. Must be either:
|
|
26
|
+
- An array of message IDs (strings)
|
|
27
|
+
- An array of message objects with `id` properties
|
|
28
|
+
|
|
29
|
+
## Returns
|
|
30
|
+
|
|
31
|
+
A Promise that resolves when all messages have been successfully deleted.
|
|
32
|
+
|
|
33
|
+
## Examples
|
|
34
|
+
|
|
35
|
+
### Delete a single message
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
// Using an array with a single string ID
|
|
39
|
+
await memory.deleteMessages(['msg-123']);
|
|
40
|
+
|
|
41
|
+
// Using an array with a single message object
|
|
42
|
+
await memory.deleteMessages([{ id: 'msg-123' }]);
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Delete multiple messages
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
// Using an array of string IDs
|
|
49
|
+
await memory.deleteMessages(['msg-1', 'msg-2', 'msg-3']);
|
|
50
|
+
|
|
51
|
+
// Using an array of message objects
|
|
52
|
+
await memory.deleteMessages([
|
|
53
|
+
{ id: 'msg-1' },
|
|
54
|
+
{ id: 'msg-2' },
|
|
55
|
+
{ id: 'msg-3' }
|
|
56
|
+
]);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Using with client SDK
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
// Get a thread instance
|
|
63
|
+
const thread = client.getAgent('my-agent').getThread('thread-123');
|
|
64
|
+
|
|
65
|
+
// Delete a single message
|
|
66
|
+
await thread.deleteMessages(['msg-123']);
|
|
67
|
+
|
|
68
|
+
// Delete multiple messages
|
|
69
|
+
await thread.deleteMessages(['msg-1', 'msg-2', 'msg-3']);
|
|
70
|
+
|
|
71
|
+
// Delete using message objects (useful when you have message data)
|
|
72
|
+
const messagesToDelete = messages.map(msg => ({ id: msg.id }));
|
|
73
|
+
await thread.deleteMessages(messagesToDelete);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Error handling
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
try {
|
|
80
|
+
await memory.deleteMessages(['msg-1', 'msg-2', 'msg-3']);
|
|
81
|
+
console.log('Messages deleted successfully');
|
|
82
|
+
} catch (error) {
|
|
83
|
+
console.error('Failed to delete messages:', error);
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Notes
|
|
88
|
+
|
|
89
|
+
- This method requires an array as input, even when deleting a single message
|
|
90
|
+
- Thread timestamps are automatically updated when messages are deleted
|
|
91
|
+
- The method automatically extracts message IDs from message objects
|
|
92
|
+
- All message IDs must be non-empty strings
|
|
93
|
+
- An empty array will result in no operation (no error thrown)
|
|
94
|
+
- Messages from different threads can be deleted in the same operation
|
|
95
|
+
- When using message objects, only the `id` property is required
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# getThreadsByResourceId Reference
|
|
2
2
|
|
|
3
|
-
The `getThreadsByResourceId` function retrieves all threads associated with a specific resource ID from storage.
|
|
3
|
+
The `getThreadsByResourceId` function retrieves all threads associated with a specific resource ID from storage. Threads can be sorted by creation or modification time in ascending or descending order.
|
|
4
4
|
|
|
5
5
|
## Usage Example
|
|
6
6
|
|
|
@@ -9,9 +9,17 @@ import { Memory } from "@mastra/core/memory";
|
|
|
9
9
|
|
|
10
10
|
const memory = new Memory(config);
|
|
11
11
|
|
|
12
|
+
// Basic usage - returns threads sorted by createdAt DESC (default)
|
|
12
13
|
const threads = await memory.getThreadsByResourceId({
|
|
13
14
|
resourceId: "resource-123",
|
|
14
15
|
});
|
|
16
|
+
|
|
17
|
+
// Custom sorting by updatedAt in ascending order
|
|
18
|
+
const threadsByUpdate = await memory.getThreadsByResourceId({
|
|
19
|
+
resourceId: "resource-123",
|
|
20
|
+
orderBy: "updatedAt",
|
|
21
|
+
sortDirection: "ASC",
|
|
22
|
+
});
|
|
15
23
|
```
|
|
16
24
|
|
|
17
25
|
## Parameters
|
|
@@ -24,9 +32,33 @@ const threads = await memory.getThreadsByResourceId({
|
|
|
24
32
|
description: "The ID of the resource whose threads are to be retrieved.",
|
|
25
33
|
isOptional: false,
|
|
26
34
|
},
|
|
35
|
+
{
|
|
36
|
+
name: "orderBy",
|
|
37
|
+
type: "ThreadOrderBy",
|
|
38
|
+
description: "Field to sort threads by. Accepts 'createdAt' or 'updatedAt'. Default: 'createdAt'",
|
|
39
|
+
isOptional: true,
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: "sortDirection",
|
|
43
|
+
type: "ThreadSortDirection",
|
|
44
|
+
description: "Sort order direction. Accepts 'ASC' or 'DESC'. Default: 'DESC'",
|
|
45
|
+
isOptional: true,
|
|
46
|
+
},
|
|
27
47
|
]}
|
|
28
48
|
/>
|
|
29
49
|
|
|
50
|
+
## Type Definitions
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
type ThreadOrderBy = 'createdAt' | 'updatedAt';
|
|
54
|
+
type ThreadSortDirection = 'ASC' | 'DESC';
|
|
55
|
+
|
|
56
|
+
interface ThreadSortOptions {
|
|
57
|
+
orderBy?: ThreadOrderBy;
|
|
58
|
+
sortDirection?: ThreadSortDirection;
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
30
62
|
## Returns
|
|
31
63
|
|
|
32
64
|
<PropertiesTable
|