@mastra/hono 0.0.0-span-scorring-test-20251124132129 → 0.0.0-top-level-fix-20251211103030

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/README.md CHANGED
@@ -1,465 +1,69 @@
1
- # @mastra/pg
1
+ # @mastra/hono
2
2
 
3
- PostgreSQL implementation for Mastra, providing both vector similarity search (using pgvector) and general storage capabilities with connection pooling and transaction support.
3
+ Hono server adapter for Mastra, enabling you to run Mastra with the [Hono](https://hono.dev) framework.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @mastra/pg
8
+ npm install @mastra/hono hono
9
9
  ```
10
10
 
11
- ## Prerequisites
12
-
13
- - PostgreSQL server with pgvector extension installed (if using vector store)
14
- - PostgreSQL 11 or higher
15
-
16
11
  ## Usage
17
12
 
18
- ### Vector Store
19
-
20
- #### Basic Configuration
21
-
22
- PgVector supports multiple connection methods:
23
-
24
- **1. Connection String (Recommended)**
25
-
26
- ```typescript
27
- import { PgVector } from '@mastra/pg';
28
-
29
- const vectorStore = new PgVector({
30
- connectionString: 'postgresql://user:pass@localhost:5432/db',
31
- });
32
- ```
33
-
34
- **2. Host/Port/Database Configuration**
35
-
36
- ```typescript
37
- const vectorStore = new PgVector({
38
- host: 'localhost',
39
- port: 5432,
40
- database: 'mydb',
41
- user: 'postgres',
42
- password: 'password',
43
- });
44
- ```
45
-
46
- > **Note:** PgVector also supports advanced configurations like Google Cloud SQL Connector via `pg.ClientConfig`.
47
-
48
- #### Advanced Options
49
-
50
- ```typescript
51
- const vectorStore = new PgVector({
52
- connectionString: 'postgresql://user:pass@localhost:5432/db',
53
- schemaName: 'custom_schema', // Use custom schema (default: public)
54
- max: 30, // Max pool connections (default: 20)
55
- idleTimeoutMillis: 60000, // Idle timeout (default: 30000)
56
- pgPoolOptions: {
57
- // Additional pg pool options
58
- connectionTimeoutMillis: 5000,
59
- allowExitOnIdle: true,
60
- },
61
- });
62
- ```
63
-
64
- #### Usage Example
65
-
66
- ```typescript
67
- // Create a new table with vector support
68
- await vectorStore.createIndex({
69
- indexName: 'my_vectors',
70
- dimension: 1536,
71
- metric: 'cosine',
72
- // Optional: Configure index type and parameters
73
- indexConfig: {
74
- type: 'hnsw', // 'ivfflat' (default), 'hnsw', or 'flat'
75
- hnsw: {
76
- m: 16, // Number of connections per layer (default: 8)
77
- efConstruction: 64 // Size of dynamic list (default: 32)
78
- }
79
- }
80
- });
81
-
82
- // Add vectors
83
- const ids = await vectorStore.upsert({
84
- indexName: 'my_vectors',
85
- vectors: [[0.1, 0.2, ...], [0.3, 0.4, ...]],
86
- metadata: [{ text: 'doc1' }, { text: 'doc2' }],
87
- });
88
-
89
- // Query vectors
90
- const results = await vectorStore.query({
91
- indexName: 'my_vectors',
92
- queryVector: [0.1, 0.2, ...],
93
- topK: 10, // topK
94
- filter: { text: 'doc1' }, // filter
95
- includeVector: false, // includeVector
96
- minScore: 0.5, // minScore
97
- });
98
-
99
- // Clean up
100
- await vectorStore.disconnect();
101
- ```
102
-
103
- ### Storage
104
-
105
- ```typescript
106
- import { PostgresStore } from '@mastra/pg';
107
-
108
- const store = new PostgresStore({
109
- host: 'localhost',
110
- port: 5432,
111
- database: 'mastra',
112
- user: 'postgres',
113
- password: 'postgres',
114
- });
115
-
116
- // Create a thread
117
- await store.saveThread({
118
- id: 'thread-123',
119
- resourceId: 'resource-456',
120
- title: 'My Thread',
121
- metadata: { key: 'value' },
122
- });
123
-
124
- // Add messages to thread
125
- await store.saveMessages([
126
- {
127
- id: 'msg-789',
128
- threadId: 'thread-123',
129
- role: 'user',
130
- type: 'text',
131
- content: [{ type: 'text', text: 'Hello' }],
132
- },
133
- ]);
134
-
135
- // Query threads and messages
136
- const savedThread = await store.getThread('thread-123');
137
- const messages = await store.getMessages('thread-123');
138
- ```
139
-
140
- ## Configuration
141
-
142
- ### Connection Methods
143
-
144
- Both `PgVector` and `PostgresStore` support multiple connection methods:
145
-
146
- 1. **Connection String**
147
-
148
- ```typescript
149
- {
150
- connectionString: 'postgresql://user:pass@localhost:5432/db';
151
- }
152
- ```
153
-
154
- 2. **Host/Port/Database**
155
- ```typescript
156
- {
157
- host: 'localhost',
158
- port: 5432,
159
- database: 'mydb',
160
- user: 'postgres',
161
- password: 'password'
162
- }
163
- ```
164
-
165
- > **Advanced:** Also supports `pg.ClientConfig` for use cases like Google Cloud SQL Connector with IAM authentication.
166
-
167
- ### Optional Configuration
168
-
169
- - `schemaName`: Custom PostgreSQL schema (default: `public`)
170
- - `ssl`: Enable SSL or provide custom SSL options (`true` | `false` | `ConnectionOptions`)
171
- - `max`: Maximum pool connections (default: `20`)
172
- - `idleTimeoutMillis`: Idle connection timeout (default: `30000`)
173
- - `pgPoolOptions`: Additional pg pool options (PgVector only)
174
-
175
- ### Default Connection Pool Settings
176
-
177
- - Maximum connections: 20
178
- - Idle timeout: 30 seconds
179
- - Connection timeout: 2 seconds
180
-
181
- ## Features
182
-
183
- ### Vector Store Features
184
-
185
- - Vector similarity search with cosine, euclidean, and dot product (inner) metrics
186
- - Advanced metadata filtering with MongoDB-like query syntax
187
- - Minimum score threshold for queries
188
- - Automatic UUID generation for vectors
189
- - Table management (create, list, describe, delete, truncate)
190
- - Configurable vector index types:
191
- - **IVFFlat** (default): Balanced speed/accuracy, auto-calculates optimal lists parameter
192
- - **HNSW**: Fastest queries, higher memory usage, best for large datasets
193
- - **Flat**: No index, 100% accuracy, best for small datasets (<1000 vectors)
194
-
195
- ### Storage Features
196
-
197
- - Thread and message storage with JSON support
198
- - Atomic transactions for data consistency
199
- - Efficient batch operations
200
- - Rich metadata support
201
- - Timestamp tracking
202
- - Cascading deletes
203
-
204
- ## Supported Filter Operators
205
-
206
- The following filter operators are supported for metadata queries:
207
-
208
- - Comparison: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`
209
- - Logical: `$and`, `$or`
210
- - Array: `$in`, `$nin`
211
- - Text: `$regex`, `$like`
212
-
213
- Example filter:
214
-
215
13
  ```typescript
216
- {
217
- $and: [{ age: { $gt: 25 } }, { tags: { $in: ['tag1', 'tag2'] } }];
218
- }
219
- ```
220
-
221
- ## Vector Index Configuration
14
+ import { Hono } from 'hono';
15
+ import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono';
16
+ import { mastra } from './mastra';
222
17
 
223
- pgvector supports three index types, each with different performance characteristics:
18
+ const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>();
19
+ const server = new MastraServer({ app, mastra });
224
20
 
225
- ### IVFFlat Index (Default)
21
+ await server.init();
226
22
 
227
- IVFFlat groups vectors into clusters for efficient searching:
228
-
229
- ```typescript
230
- await vectorStore.createIndex({
231
- indexName: 'my_vectors',
232
- dimension: 1536,
233
- metric: 'cosine',
234
- indexConfig: {
235
- type: 'ivfflat',
236
- ivf: {
237
- lists: 1000, // Number of clusters (default: auto-calculated as sqrt(rows) * 2)
238
- },
239
- },
240
- });
23
+ export default app;
241
24
  ```
242
25
 
243
- - **Best for:** Medium to large datasets (10K-1M vectors)
244
- - **Build time:** Minutes for millions of vectors
245
- - **Query speed:** Fast (tens of milliseconds)
246
- - **Memory:** Moderate
247
- - **Accuracy:** ~95-99%
26
+ ## Adding Custom Routes
248
27
 
249
- ### HNSW Index
250
-
251
- HNSW builds a graph structure for extremely fast searches:
28
+ Add routes directly to the Hono app with access to Mastra context:
252
29
 
253
30
  ```typescript
254
- await vectorStore.createIndex({
255
- indexName: 'my_vectors',
256
- dimension: 1536,
257
- metric: 'dotproduct', // Recommended for normalized embeddings (OpenAI, etc.)
258
- indexConfig: {
259
- type: 'hnsw',
260
- hnsw: {
261
- m: 16, // Connections per layer (default: 8, range: 2-100)
262
- efConstruction: 64, // Dynamic list size (default: 32, range: 4-1000)
263
- },
264
- },
31
+ // Routes added after init() have access to Mastra context
32
+ app.get('/health', c => {
33
+ const mastraInstance = c.get('mastra');
34
+ const agents = Object.keys(mastraInstance.listAgents());
35
+ return c.json({ status: 'ok', agents });
265
36
  });
266
37
  ```
267
38
 
268
- - **Best for:** Large datasets (100K+ vectors) requiring fastest searches
269
- - **Build time:** Can take hours for large datasets
270
- - **Query speed:** Very fast (milliseconds even for millions)
271
- - **Memory:** High (can be 2-3x vector size)
272
- - **Accuracy:** ~99%
273
-
274
- **Tuning HNSW:**
275
-
276
- - Higher `m`: Better accuracy, more memory (16-32 for high accuracy)
277
- - Higher `efConstruction`: Better index quality, slower builds (64-200 for quality)
278
-
279
- ### Flat Index (No Index)
280
-
281
- Uses sequential scan for 100% accuracy:
39
+ ## Configuration Options
282
40
 
283
41
  ```typescript
284
- await vectorStore.createIndex({
285
- indexName: 'my_vectors',
286
- dimension: 1536,
287
- metric: 'cosine',
288
- indexConfig: {
289
- type: 'flat',
42
+ const server = new MastraServer({
43
+ app,
44
+ mastra,
45
+ prefix: '/api/v2', // Route prefix
46
+ openapiPath: '/openapi.json', // OpenAPI spec endpoint
47
+ bodyLimitOptions: {
48
+ maxSize: 10 * 1024 * 1024, // 10MB
49
+ onError: err => ({ error: 'Payload too large' }),
290
50
  },
51
+ streamOptions: { redact: true }, // Redact sensitive data from streams
291
52
  });
292
53
  ```
293
54
 
294
- - **Best for:** Small datasets (<1000 vectors) or when 100% accuracy is required
295
- - **Build time:** None
296
- - **Query speed:** Slow for large datasets (linear scan)
297
- - **Memory:** Minimal (just vectors)
298
- - **Accuracy:** 100%
299
-
300
- ### Distance Metrics
301
-
302
- Choose the appropriate metric for your embeddings:
303
-
304
- - **`cosine`** (default): Angular similarity, good for text embeddings
305
- - **`euclidean`**: L2 distance, for unnormalized embeddings
306
- - **`dotproduct`**: Dot product, optimal for normalized embeddings (OpenAI, Cohere)
307
-
308
- ### Index Recreation
309
-
310
- The system automatically detects configuration changes and only rebuilds indexes when necessary, preventing the performance issues from unnecessary recreations.
311
-
312
- **Important behaviors:**
313
-
314
- - If no `indexConfig` is provided, existing indexes are preserved as-is
315
- - If `indexConfig` is provided, indexes are only rebuilt if the configuration differs
316
- - New indexes default to IVFFlat with cosine distance when no config is specified
317
-
318
- ## Vector Store Methods
319
-
320
- - `createIndex({indexName, dimension, metric?, indexConfig?, buildIndex?})`: Create a new table with vector support
321
- - `buildIndex({indexName, metric?, indexConfig?})`: Build or rebuild vector index
322
- - `upsert({indexName, vectors, metadata?, ids?})`: Add or update vectors
323
- - `query({indexName, queryVector, topK?, filter?, includeVector?, minScore?})`: Search for similar vectors
324
- - `listIndexes()`: List all vector-enabled tables
325
- - `describeIndex(indexName)`: Get table statistics and index configuration
326
- - `deleteIndex(indexName)`: Delete a table
327
- - `truncateIndex(indexName)`: Remove all data from a table
328
- - `disconnect()`: Close all database connections
329
-
330
- ## Storage Methods
331
-
332
- - `saveThread(thread)`: Create or update a thread
333
- - `getThread(threadId)`: Get a thread by ID
334
- - `deleteThread(threadId)`: Delete a thread and its messages
335
- - `saveMessages(messages)`: Save multiple messages in a transaction
336
- - `getMessages(threadId)`: Get all messages for a thread
337
- - `deleteMessages(messageIds)`: Delete specific messages
338
-
339
- ## Index Management
340
-
341
- The PostgreSQL store provides comprehensive index management capabilities to optimize query performance.
342
-
343
- ### Automatic Performance Indexes
344
-
345
- PostgreSQL storage automatically creates composite indexes during initialization for common query patterns:
346
-
347
- - `mastra_threads_resourceid_createdat_idx`: (resourceId, createdAt DESC)
348
- - `mastra_messages_thread_id_createdat_idx`: (thread_id, createdAt DESC)
349
- - `mastra_traces_name_starttime_idx`: (name, startTime DESC)
350
- - `mastra_evals_agent_name_created_at_idx`: (agent_name, created_at DESC)
351
-
352
- These indexes significantly improve performance for filtered queries with sorting.
353
-
354
- ### Creating Custom Indexes
355
-
356
- Create additional indexes to optimize specific query patterns:
357
-
358
- ```typescript
359
- // Basic index for common queries
360
- await store.createIndex({
361
- name: 'idx_threads_resource',
362
- table: 'mastra_threads',
363
- columns: ['resourceId'],
364
- });
365
-
366
- // Composite index with sort order for filtering + sorting
367
- await store.createIndex({
368
- name: 'idx_messages_composite',
369
- table: 'mastra_messages',
370
- columns: ['thread_id', 'createdAt DESC'],
371
- });
372
-
373
- // GIN index for JSONB columns (fast JSON queries)
374
- await store.createIndex({
375
- name: 'idx_traces_attributes',
376
- table: 'mastra_traces',
377
- columns: ['attributes'],
378
- method: 'gin',
379
- });
380
- ```
381
-
382
- For more advanced use cases, you can also use:
383
-
384
- - `unique: true` for unique constraints
385
- - `where: 'condition'` for partial indexes
386
- - `method: 'brin'` for time-series data
387
- - `storage: { fillfactor: 90 }` for update-heavy tables
388
- - `concurrent: true` for non-blocking creation (default)
389
-
390
- ### Managing Indexes
391
-
392
- ```typescript
393
- // List all indexes
394
- const allIndexes = await store.listIndexes();
395
-
396
- // List indexes for specific table
397
- const threadIndexes = await store.listIndexes('mastra_threads');
398
-
399
- // Get detailed statistics for an index
400
- const stats = await store.describeIndex('idx_threads_resource');
401
- console.log(stats);
402
- // {
403
- // name: 'idx_threads_resource',
404
- // table: 'mastra_threads',
405
- // columns: ['resourceId', 'createdAt'],
406
- // unique: false,
407
- // size: '128 KB',
408
- // definition: 'CREATE INDEX idx_threads_resource...',
409
- // method: 'btree',
410
- // scans: 1542, // Number of index scans
411
- // tuples_read: 45230, // Tuples read via index
412
- // tuples_fetched: 12050 // Tuples fetched via index
413
- // }
414
-
415
- // Drop an index
416
- await store.dropIndex('idx_threads_status');
417
- ```
418
-
419
- ### Index Types and Use Cases
55
+ ## Context Variables
420
56
 
421
- | Index Type | Best For | Storage | Speed |
422
- | ------------------- | --------------------------------------- | ---------- | -------------------------- |
423
- | **btree** (default) | Range queries, sorting, general purpose | Moderate | Fast |
424
- | **hash** | Equality comparisons only | Small | Very fast for `=` |
425
- | **gin** | JSONB, arrays, full-text search | Large | Fast for contains |
426
- | **gist** | Geometric data, full-text search | Moderate | Fast for nearest-neighbor |
427
- | **spgist** | Non-balanced data, text patterns | Small | Fast for specific patterns |
428
- | **brin** | Large tables with natural ordering | Very small | Fast for ranges |
57
+ Access these in route handlers via `c.get()`:
429
58
 
430
- ### Index Options
431
-
432
- - `name` (required): Index name
433
- - `table` (required): Table name
434
- - `columns` (required): Array of column names (can include DESC/ASC)
435
- - `unique`: Create unique index (default: false)
436
- - `concurrent`: Non-blocking index creation (default: true)
437
- - `where`: Partial index condition
438
- - `method`: Index type ('btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin')
439
- - `opclass`: Operator class for GIN/GIST indexes
440
- - `storage`: Storage parameters (e.g., { fillfactor: 90 })
441
- - `tablespace`: Tablespace name for index placement
442
-
443
- ### Monitoring Index Performance
444
-
445
- ```typescript
446
- // Check index usage statistics
447
- const stats = await store.describeIndex('idx_threads_resource');
448
-
449
- // Identify unused indexes
450
- if (stats.scans === 0) {
451
- console.log(`Index ${stats.name} is unused - consider removing`);
452
- await store.dropIndex(stats.name);
453
- }
454
-
455
- // Monitor index efficiency
456
- const efficiency = stats.tuples_fetched / stats.tuples_read;
457
- if (efficiency < 0.5) {
458
- console.log(`Index ${stats.name} has low efficiency: ${efficiency}`);
459
- }
460
- ```
59
+ | Key | Description |
60
+ | ---------------- | --------------------------- |
61
+ | `mastra` | Mastra instance |
62
+ | `requestContext` | Request context map |
63
+ | `abortSignal` | Request cancellation signal |
64
+ | `tools` | Available tools |
461
65
 
462
66
  ## Related Links
463
67
 
464
- - [pgvector Documentation](https://github.com/pgvector/pgvector)
465
- - [PostgreSQL Documentation](https://www.postgresql.org/docs/)
68
+ - [Server Adapters Documentation](https://mastra.ai/docs/v1/server-db/server-adapters)
69
+ - [Hono Documentation](https://hono.dev)
@@ -0,0 +1,11 @@
1
+ import type { ContextWithMastra } from '@mastra/core/server';
2
+ import type { Next } from 'hono';
3
+ export declare const authenticationMiddleware: (c: ContextWithMastra, next: Next) => Promise<void | (Response & import("hono").TypedResponse<{
4
+ error: string;
5
+ }, 401, "json">)>;
6
+ export declare const authorizationMiddleware: (c: ContextWithMastra, next: Next) => Promise<void | (Response & import("hono").TypedResponse<{
7
+ error: string;
8
+ }, 403, "json">) | (Response & import("hono").TypedResponse<{
9
+ error: string;
10
+ }, 500, "json">)>;
11
+ //# sourceMappingURL=auth-middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-middleware.d.ts","sourceRoot":"","sources":["../src/auth-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAQ7D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,eAAO,MAAM,wBAAwB,GAAU,GAAG,iBAAiB,EAAE,MAAM,IAAI;;iBAgE9E,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAAU,GAAG,iBAAiB,EAAE,MAAM,IAAI;;;;iBAkF7E,CAAC"}