agentdb 1.2.0 ā 1.3.1
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 +180 -33
- package/dist/cli/agentdb-cli.d.ts +1 -0
- package/dist/cli/agentdb-cli.d.ts.map +1 -1
- package/dist/cli/agentdb-cli.js +108 -134
- package/dist/cli/agentdb-cli.js.map +1 -1
- package/dist/controllers/CausalMemoryGraph.d.ts.map +1 -1
- package/dist/controllers/CausalMemoryGraph.js +3 -3
- package/dist/controllers/CausalMemoryGraph.js.map +1 -1
- package/dist/controllers/CausalRecall.d.ts +25 -0
- package/dist/controllers/CausalRecall.d.ts.map +1 -1
- package/dist/controllers/CausalRecall.js +44 -1
- package/dist/controllers/CausalRecall.js.map +1 -1
- package/dist/controllers/EmbeddingService.d.ts.map +1 -1
- package/dist/controllers/EmbeddingService.js +4 -0
- package/dist/controllers/EmbeddingService.js.map +1 -1
- package/dist/controllers/ExplainableRecall.js +1 -1
- package/dist/controllers/LearningSystem.d.ts +194 -0
- package/dist/controllers/LearningSystem.d.ts.map +1 -0
- package/dist/controllers/LearningSystem.js +929 -0
- package/dist/controllers/LearningSystem.js.map +1 -0
- package/dist/controllers/NightlyLearner.d.ts.map +1 -1
- package/dist/controllers/NightlyLearner.js +9 -1
- package/dist/controllers/NightlyLearner.js.map +1 -1
- package/dist/controllers/ReasoningBank.d.ts +96 -0
- package/dist/controllers/ReasoningBank.d.ts.map +1 -0
- package/dist/controllers/ReasoningBank.js +302 -0
- package/dist/controllers/ReasoningBank.js.map +1 -0
- package/dist/controllers/ReflexionMemory.d.ts.map +1 -1
- package/dist/controllers/ReflexionMemory.js +4 -0
- package/dist/controllers/ReflexionMemory.js.map +1 -1
- package/dist/controllers/SkillLibrary.d.ts +37 -3
- package/dist/controllers/SkillLibrary.d.ts.map +1 -1
- package/dist/controllers/SkillLibrary.js +196 -15
- package/dist/controllers/SkillLibrary.js.map +1 -1
- package/dist/mcp/agentdb-mcp-server.d.ts +8 -0
- package/dist/mcp/agentdb-mcp-server.d.ts.map +1 -0
- package/dist/mcp/agentdb-mcp-server.js +1485 -352
- package/dist/mcp/agentdb-mcp-server.js.map +1 -0
- package/dist/mcp/learning-tools-handlers.d.ts +16 -0
- package/dist/mcp/learning-tools-handlers.d.ts.map +1 -0
- package/dist/mcp/learning-tools-handlers.js +105 -0
- package/dist/mcp/learning-tools-handlers.js.map +1 -0
- package/dist/optimizations/QueryOptimizer.d.ts.map +1 -1
- package/dist/optimizations/QueryOptimizer.js +3 -1
- package/dist/optimizations/QueryOptimizer.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/agentdb-cli.ts +136 -51
- package/src/controllers/CausalMemoryGraph.ts +2 -3
- package/src/controllers/CausalRecall.ts +73 -1
- package/src/controllers/EmbeddingService.ts +6 -1
- package/src/controllers/ExplainableRecall.ts +1 -1
- package/src/controllers/LearningSystem.ts +1286 -0
- package/src/controllers/NightlyLearner.ts +11 -1
- package/src/controllers/ReasoningBank.ts +411 -0
- package/src/controllers/ReflexionMemory.ts +4 -0
- package/src/controllers/SkillLibrary.ts +254 -16
- package/src/mcp/agentdb-mcp-server.ts +1710 -0
- package/src/mcp/learning-tools-handlers.ts +106 -0
- package/src/optimizations/QueryOptimizer.ts +4 -2
- package/dist/benchmarks/comprehensive-benchmark.js +0 -664
- package/dist/benchmarks/frontier-benchmark.js +0 -419
- package/dist/benchmarks/reflexion-benchmark.js +0 -370
- package/dist/cli/agentdb-cli.js.backup +0 -718
- package/dist/schemas/frontier-schema.sql +0 -341
- package/dist/schemas/schema.sql +0 -382
- package/dist/tests/frontier-features.test.js +0 -665
|
@@ -0,0 +1,1710 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* AgentDB MCP Server
|
|
4
|
+
* Production-ready MCP server for Claude Desktop integration
|
|
5
|
+
* Exposes AgentDB frontier memory features + core vector DB operations via MCP protocol
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
9
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
10
|
+
import {
|
|
11
|
+
CallToolRequestSchema,
|
|
12
|
+
ListToolsRequestSchema,
|
|
13
|
+
} from '@modelcontextprotocol/sdk/types.js';
|
|
14
|
+
import Database from 'better-sqlite3';
|
|
15
|
+
import { CausalMemoryGraph } from '../controllers/CausalMemoryGraph.js';
|
|
16
|
+
import { CausalRecall } from '../controllers/CausalRecall.js';
|
|
17
|
+
import { ReflexionMemory } from '../controllers/ReflexionMemory.js';
|
|
18
|
+
import { SkillLibrary } from '../controllers/SkillLibrary.js';
|
|
19
|
+
import { NightlyLearner } from '../controllers/NightlyLearner.js';
|
|
20
|
+
import { LearningSystem } from '../controllers/LearningSystem.js';
|
|
21
|
+
import { EmbeddingService } from '../controllers/EmbeddingService.js';
|
|
22
|
+
import { BatchOperations } from '../optimizations/BatchOperations.js';
|
|
23
|
+
import { ReasoningBank } from '../controllers/ReasoningBank.js';
|
|
24
|
+
import * as path from 'path';
|
|
25
|
+
import * as fs from 'fs';
|
|
26
|
+
|
|
27
|
+
// ============================================================================
|
|
28
|
+
// Initialize AgentDB Controllers
|
|
29
|
+
// ============================================================================
|
|
30
|
+
const dbPath = process.env.AGENTDB_PATH || './agentdb.db';
|
|
31
|
+
const db = new Database(dbPath);
|
|
32
|
+
|
|
33
|
+
// Configure for performance
|
|
34
|
+
db.pragma('journal_mode = WAL');
|
|
35
|
+
db.pragma('synchronous = NORMAL');
|
|
36
|
+
db.pragma('cache_size = -64000');
|
|
37
|
+
|
|
38
|
+
// Initialize embedding service
|
|
39
|
+
const embeddingService = new EmbeddingService({
|
|
40
|
+
model: 'Xenova/all-MiniLM-L6-v2',
|
|
41
|
+
dimension: 384,
|
|
42
|
+
provider: 'transformers'
|
|
43
|
+
});
|
|
44
|
+
await embeddingService.initialize();
|
|
45
|
+
|
|
46
|
+
// Initialize all controllers
|
|
47
|
+
const causalGraph = new CausalMemoryGraph(db);
|
|
48
|
+
const reflexion = new ReflexionMemory(db, embeddingService);
|
|
49
|
+
const skills = new SkillLibrary(db, embeddingService);
|
|
50
|
+
const causalRecall = new CausalRecall(db, embeddingService);
|
|
51
|
+
const learner = new NightlyLearner(db, embeddingService);
|
|
52
|
+
const learningSystem = new LearningSystem(db, embeddingService);
|
|
53
|
+
const batchOps = new BatchOperations(db, embeddingService);
|
|
54
|
+
const reasoningBank = new ReasoningBank(db, embeddingService);
|
|
55
|
+
|
|
56
|
+
// ============================================================================
|
|
57
|
+
// Helper Functions for Core Vector DB Operations
|
|
58
|
+
// ============================================================================
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Initialize database schema
|
|
62
|
+
*/
|
|
63
|
+
function initializeSchema(): void {
|
|
64
|
+
// Episodes table (vector store)
|
|
65
|
+
db.exec(`
|
|
66
|
+
CREATE TABLE IF NOT EXISTS episodes (
|
|
67
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
68
|
+
ts INTEGER DEFAULT (strftime('%s', 'now')),
|
|
69
|
+
session_id TEXT NOT NULL,
|
|
70
|
+
task TEXT NOT NULL,
|
|
71
|
+
input TEXT,
|
|
72
|
+
output TEXT,
|
|
73
|
+
critique TEXT,
|
|
74
|
+
reward REAL NOT NULL,
|
|
75
|
+
success INTEGER NOT NULL,
|
|
76
|
+
latency_ms INTEGER,
|
|
77
|
+
tokens_used INTEGER,
|
|
78
|
+
tags TEXT,
|
|
79
|
+
metadata TEXT
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
CREATE INDEX IF NOT EXISTS idx_episodes_session ON episodes(session_id);
|
|
83
|
+
CREATE INDEX IF NOT EXISTS idx_episodes_task ON episodes(task);
|
|
84
|
+
CREATE INDEX IF NOT EXISTS idx_episodes_reward ON episodes(reward);
|
|
85
|
+
CREATE INDEX IF NOT EXISTS idx_episodes_success ON episodes(success);
|
|
86
|
+
`);
|
|
87
|
+
|
|
88
|
+
// Episode embeddings (vector storage)
|
|
89
|
+
db.exec(`
|
|
90
|
+
CREATE TABLE IF NOT EXISTS episode_embeddings (
|
|
91
|
+
episode_id INTEGER PRIMARY KEY,
|
|
92
|
+
embedding BLOB NOT NULL,
|
|
93
|
+
FOREIGN KEY (episode_id) REFERENCES episodes(id) ON DELETE CASCADE
|
|
94
|
+
);
|
|
95
|
+
`);
|
|
96
|
+
|
|
97
|
+
// Skills table
|
|
98
|
+
db.exec(`
|
|
99
|
+
CREATE TABLE IF NOT EXISTS skills (
|
|
100
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
101
|
+
ts INTEGER DEFAULT (strftime('%s', 'now')),
|
|
102
|
+
name TEXT UNIQUE NOT NULL,
|
|
103
|
+
description TEXT NOT NULL,
|
|
104
|
+
signature TEXT,
|
|
105
|
+
code TEXT,
|
|
106
|
+
success_rate REAL DEFAULT 0.0,
|
|
107
|
+
uses INTEGER DEFAULT 0,
|
|
108
|
+
avg_reward REAL DEFAULT 0.0,
|
|
109
|
+
avg_latency_ms REAL DEFAULT 0.0,
|
|
110
|
+
tags TEXT,
|
|
111
|
+
metadata TEXT
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
CREATE INDEX IF NOT EXISTS idx_skills_success_rate ON skills(success_rate);
|
|
115
|
+
`);
|
|
116
|
+
|
|
117
|
+
// Skill embeddings
|
|
118
|
+
db.exec(`
|
|
119
|
+
CREATE TABLE IF NOT EXISTS skill_embeddings (
|
|
120
|
+
skill_id INTEGER PRIMARY KEY,
|
|
121
|
+
embedding BLOB NOT NULL,
|
|
122
|
+
FOREIGN KEY (skill_id) REFERENCES skills(id) ON DELETE CASCADE
|
|
123
|
+
);
|
|
124
|
+
`);
|
|
125
|
+
|
|
126
|
+
// Causal edges table
|
|
127
|
+
db.exec(`
|
|
128
|
+
CREATE TABLE IF NOT EXISTS causal_edges (
|
|
129
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
130
|
+
ts INTEGER DEFAULT (strftime('%s', 'now')),
|
|
131
|
+
from_memory_id INTEGER NOT NULL,
|
|
132
|
+
from_memory_type TEXT NOT NULL,
|
|
133
|
+
to_memory_id INTEGER NOT NULL,
|
|
134
|
+
to_memory_type TEXT NOT NULL,
|
|
135
|
+
similarity REAL DEFAULT 0.0,
|
|
136
|
+
uplift REAL NOT NULL,
|
|
137
|
+
confidence REAL DEFAULT 0.95,
|
|
138
|
+
sample_size INTEGER DEFAULT 0,
|
|
139
|
+
evidence_ids TEXT
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
CREATE INDEX IF NOT EXISTS idx_causal_from ON causal_edges(from_memory_id, from_memory_type);
|
|
143
|
+
CREATE INDEX IF NOT EXISTS idx_causal_to ON causal_edges(to_memory_id, to_memory_type);
|
|
144
|
+
CREATE INDEX IF NOT EXISTS idx_causal_uplift ON causal_edges(uplift);
|
|
145
|
+
`);
|
|
146
|
+
|
|
147
|
+
// Causal experiments
|
|
148
|
+
db.exec(`
|
|
149
|
+
CREATE TABLE IF NOT EXISTS causal_experiments (
|
|
150
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
151
|
+
ts INTEGER DEFAULT (strftime('%s', 'now')),
|
|
152
|
+
intervention_id INTEGER NOT NULL,
|
|
153
|
+
control_outcome REAL NOT NULL,
|
|
154
|
+
treatment_outcome REAL NOT NULL,
|
|
155
|
+
uplift REAL NOT NULL,
|
|
156
|
+
sample_size INTEGER DEFAULT 1,
|
|
157
|
+
metadata TEXT
|
|
158
|
+
);
|
|
159
|
+
`);
|
|
160
|
+
|
|
161
|
+
// Causal observations
|
|
162
|
+
db.exec(`
|
|
163
|
+
CREATE TABLE IF NOT EXISTS causal_observations (
|
|
164
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
165
|
+
ts INTEGER DEFAULT (strftime('%s', 'now')),
|
|
166
|
+
action TEXT NOT NULL,
|
|
167
|
+
outcome TEXT NOT NULL,
|
|
168
|
+
reward REAL NOT NULL,
|
|
169
|
+
session_id TEXT,
|
|
170
|
+
metadata TEXT
|
|
171
|
+
);
|
|
172
|
+
`);
|
|
173
|
+
|
|
174
|
+
// Provenance certificates
|
|
175
|
+
db.exec(`
|
|
176
|
+
CREATE TABLE IF NOT EXISTS provenance_certificates (
|
|
177
|
+
id TEXT PRIMARY KEY,
|
|
178
|
+
ts INTEGER DEFAULT (strftime('%s', 'now')),
|
|
179
|
+
query_id TEXT NOT NULL,
|
|
180
|
+
agent_id TEXT NOT NULL,
|
|
181
|
+
query_text TEXT NOT NULL,
|
|
182
|
+
retrieval_method TEXT NOT NULL,
|
|
183
|
+
source_ids TEXT NOT NULL,
|
|
184
|
+
certificate_hash TEXT NOT NULL,
|
|
185
|
+
metadata TEXT
|
|
186
|
+
);
|
|
187
|
+
`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Serialize embedding to BLOB
|
|
192
|
+
*/
|
|
193
|
+
function serializeEmbedding(embedding: Float32Array): Buffer {
|
|
194
|
+
return Buffer.from(embedding.buffer);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Deserialize embedding from BLOB
|
|
199
|
+
*/
|
|
200
|
+
function deserializeEmbedding(blob: Buffer): Float32Array {
|
|
201
|
+
return new Float32Array(blob.buffer, blob.byteOffset, blob.byteLength / 4);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Calculate cosine similarity between two vectors
|
|
206
|
+
*/
|
|
207
|
+
function cosineSimilarity(a: Float32Array, b: Float32Array): number {
|
|
208
|
+
if (a.length !== b.length) {
|
|
209
|
+
throw new Error('Vectors must have same length');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
let dotProduct = 0;
|
|
213
|
+
let normA = 0;
|
|
214
|
+
let normB = 0;
|
|
215
|
+
|
|
216
|
+
for (let i = 0; i < a.length; i++) {
|
|
217
|
+
dotProduct += a[i] * b[i];
|
|
218
|
+
normA += a[i] * a[i];
|
|
219
|
+
normB += b[i] * b[i];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ============================================================================
|
|
226
|
+
// MCP Server Setup
|
|
227
|
+
// ============================================================================
|
|
228
|
+
const server = new Server(
|
|
229
|
+
{
|
|
230
|
+
name: 'agentdb',
|
|
231
|
+
version: '1.3.0',
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
capabilities: {
|
|
235
|
+
tools: {},
|
|
236
|
+
},
|
|
237
|
+
}
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
// ============================================================================
|
|
241
|
+
// Tool Definitions
|
|
242
|
+
// ============================================================================
|
|
243
|
+
const tools = [
|
|
244
|
+
// ==========================================================================
|
|
245
|
+
// CORE VECTOR DB OPERATIONS (NEW)
|
|
246
|
+
// ==========================================================================
|
|
247
|
+
{
|
|
248
|
+
name: 'agentdb_init',
|
|
249
|
+
description: 'Initialize AgentDB database with schema and optimizations. Creates all required tables for vector storage, causal memory, skills, and provenance tracking.',
|
|
250
|
+
inputSchema: {
|
|
251
|
+
type: 'object',
|
|
252
|
+
properties: {
|
|
253
|
+
db_path: { type: 'string', description: 'Database file path (optional, defaults to ./agentdb.db)', default: './agentdb.db' },
|
|
254
|
+
reset: { type: 'boolean', description: 'Reset database (delete existing)', default: false },
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
{
|
|
259
|
+
name: 'agentdb_insert',
|
|
260
|
+
description: 'Insert a single vector with metadata into AgentDB. Automatically generates embeddings for the provided text.',
|
|
261
|
+
inputSchema: {
|
|
262
|
+
type: 'object',
|
|
263
|
+
properties: {
|
|
264
|
+
text: { type: 'string', description: 'Text content to embed and store' },
|
|
265
|
+
metadata: { type: 'object', description: 'Additional metadata (JSON object)' },
|
|
266
|
+
session_id: { type: 'string', description: 'Session identifier', default: 'default' },
|
|
267
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Tags for categorization' },
|
|
268
|
+
},
|
|
269
|
+
required: ['text'],
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
name: 'agentdb_insert_batch',
|
|
274
|
+
description: 'Batch insert multiple vectors efficiently using transactions and parallel embedding generation. Optimized for large datasets.',
|
|
275
|
+
inputSchema: {
|
|
276
|
+
type: 'object',
|
|
277
|
+
properties: {
|
|
278
|
+
items: {
|
|
279
|
+
type: 'array',
|
|
280
|
+
items: {
|
|
281
|
+
type: 'object',
|
|
282
|
+
properties: {
|
|
283
|
+
text: { type: 'string', description: 'Text content to embed' },
|
|
284
|
+
metadata: { type: 'object', description: 'Metadata (JSON)' },
|
|
285
|
+
session_id: { type: 'string', description: 'Session ID' },
|
|
286
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
287
|
+
},
|
|
288
|
+
required: ['text'],
|
|
289
|
+
},
|
|
290
|
+
description: 'Array of items to insert',
|
|
291
|
+
},
|
|
292
|
+
batch_size: { type: 'number', description: 'Batch size for processing', default: 100 },
|
|
293
|
+
},
|
|
294
|
+
required: ['items'],
|
|
295
|
+
},
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
name: 'agentdb_search',
|
|
299
|
+
description: 'Semantic k-NN vector search using cosine similarity. Returns the most relevant results ranked by similarity score.',
|
|
300
|
+
inputSchema: {
|
|
301
|
+
type: 'object',
|
|
302
|
+
properties: {
|
|
303
|
+
query: { type: 'string', description: 'Search query text' },
|
|
304
|
+
k: { type: 'number', description: 'Number of results to return', default: 10 },
|
|
305
|
+
min_similarity: { type: 'number', description: 'Minimum similarity threshold (0-1)', default: 0.0 },
|
|
306
|
+
filters: {
|
|
307
|
+
type: 'object',
|
|
308
|
+
properties: {
|
|
309
|
+
session_id: { type: 'string', description: 'Filter by session ID' },
|
|
310
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },
|
|
311
|
+
min_reward: { type: 'number', description: 'Minimum reward threshold' },
|
|
312
|
+
},
|
|
313
|
+
description: 'Optional filters',
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
required: ['query'],
|
|
317
|
+
},
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
name: 'agentdb_delete',
|
|
321
|
+
description: 'Delete vector(s) from AgentDB by ID or filters. Supports single ID deletion or bulk deletion with conditions.',
|
|
322
|
+
inputSchema: {
|
|
323
|
+
type: 'object',
|
|
324
|
+
properties: {
|
|
325
|
+
id: { type: 'number', description: 'Specific vector ID to delete' },
|
|
326
|
+
filters: {
|
|
327
|
+
type: 'object',
|
|
328
|
+
properties: {
|
|
329
|
+
session_id: { type: 'string', description: 'Delete all vectors with this session ID' },
|
|
330
|
+
before_timestamp: { type: 'number', description: 'Delete vectors before this Unix timestamp' },
|
|
331
|
+
},
|
|
332
|
+
description: 'Bulk deletion filters (used if id not provided)',
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
},
|
|
337
|
+
|
|
338
|
+
// ==========================================================================
|
|
339
|
+
// FRONTIER MEMORY FEATURES (EXISTING)
|
|
340
|
+
// ==========================================================================
|
|
341
|
+
{
|
|
342
|
+
name: 'reflexion_store',
|
|
343
|
+
description: 'Store an episode with self-critique for reflexion-based learning',
|
|
344
|
+
inputSchema: {
|
|
345
|
+
type: 'object',
|
|
346
|
+
properties: {
|
|
347
|
+
session_id: { type: 'string', description: 'Session identifier' },
|
|
348
|
+
task: { type: 'string', description: 'Task description' },
|
|
349
|
+
reward: { type: 'number', description: 'Task reward (0-1)' },
|
|
350
|
+
success: { type: 'boolean', description: 'Whether task succeeded' },
|
|
351
|
+
critique: { type: 'string', description: 'Self-critique reflection' },
|
|
352
|
+
input: { type: 'string', description: 'Task input' },
|
|
353
|
+
output: { type: 'string', description: 'Task output' },
|
|
354
|
+
latency_ms: { type: 'number', description: 'Execution latency' },
|
|
355
|
+
tokens: { type: 'number', description: 'Tokens used' },
|
|
356
|
+
},
|
|
357
|
+
required: ['session_id', 'task', 'reward', 'success'],
|
|
358
|
+
},
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
name: 'reflexion_retrieve',
|
|
362
|
+
description: 'Retrieve relevant past episodes for learning from experience',
|
|
363
|
+
inputSchema: {
|
|
364
|
+
type: 'object',
|
|
365
|
+
properties: {
|
|
366
|
+
task: { type: 'string', description: 'Task to find similar episodes for' },
|
|
367
|
+
k: { type: 'number', description: 'Number of episodes to retrieve', default: 5 },
|
|
368
|
+
only_failures: { type: 'boolean', description: 'Only retrieve failures' },
|
|
369
|
+
only_successes: { type: 'boolean', description: 'Only retrieve successes' },
|
|
370
|
+
min_reward: { type: 'number', description: 'Minimum reward threshold' },
|
|
371
|
+
},
|
|
372
|
+
required: ['task'],
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
name: 'skill_create',
|
|
377
|
+
description: 'Create a reusable skill in the skill library',
|
|
378
|
+
inputSchema: {
|
|
379
|
+
type: 'object',
|
|
380
|
+
properties: {
|
|
381
|
+
name: { type: 'string', description: 'Skill name' },
|
|
382
|
+
description: { type: 'string', description: 'What the skill does' },
|
|
383
|
+
code: { type: 'string', description: 'Skill implementation code' },
|
|
384
|
+
success_rate: { type: 'number', description: 'Initial success rate' },
|
|
385
|
+
},
|
|
386
|
+
required: ['name', 'description'],
|
|
387
|
+
},
|
|
388
|
+
},
|
|
389
|
+
{
|
|
390
|
+
name: 'skill_search',
|
|
391
|
+
description: 'Search for applicable skills by semantic similarity',
|
|
392
|
+
inputSchema: {
|
|
393
|
+
type: 'object',
|
|
394
|
+
properties: {
|
|
395
|
+
task: { type: 'string', description: 'Task to find skills for' },
|
|
396
|
+
k: { type: 'number', description: 'Number of skills to return', default: 10 },
|
|
397
|
+
min_success_rate: { type: 'number', description: 'Minimum success rate filter' },
|
|
398
|
+
},
|
|
399
|
+
required: ['task'],
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
{
|
|
403
|
+
name: 'causal_add_edge',
|
|
404
|
+
description: 'Add a causal relationship between actions and outcomes',
|
|
405
|
+
inputSchema: {
|
|
406
|
+
type: 'object',
|
|
407
|
+
properties: {
|
|
408
|
+
cause: { type: 'string', description: 'Causal action/intervention' },
|
|
409
|
+
effect: { type: 'string', description: 'Observed effect/outcome' },
|
|
410
|
+
uplift: { type: 'number', description: 'Causal uplift magnitude' },
|
|
411
|
+
confidence: { type: 'number', description: 'Confidence in causal claim (0-1)', default: 0.95 },
|
|
412
|
+
sample_size: { type: 'number', description: 'Number of observations', default: 0 },
|
|
413
|
+
},
|
|
414
|
+
required: ['cause', 'effect', 'uplift'],
|
|
415
|
+
},
|
|
416
|
+
},
|
|
417
|
+
{
|
|
418
|
+
name: 'causal_query',
|
|
419
|
+
description: 'Query causal effects to understand what actions cause what outcomes',
|
|
420
|
+
inputSchema: {
|
|
421
|
+
type: 'object',
|
|
422
|
+
properties: {
|
|
423
|
+
cause: { type: 'string', description: 'Filter by cause (optional)' },
|
|
424
|
+
effect: { type: 'string', description: 'Filter by effect (optional)' },
|
|
425
|
+
min_confidence: { type: 'number', description: 'Minimum confidence', default: 0.5 },
|
|
426
|
+
min_uplift: { type: 'number', description: 'Minimum uplift', default: 0.0 },
|
|
427
|
+
limit: { type: 'number', description: 'Maximum results', default: 10 },
|
|
428
|
+
},
|
|
429
|
+
},
|
|
430
|
+
},
|
|
431
|
+
{
|
|
432
|
+
name: 'recall_with_certificate',
|
|
433
|
+
description: 'Retrieve memories with causal utility scoring and provenance certificate',
|
|
434
|
+
inputSchema: {
|
|
435
|
+
type: 'object',
|
|
436
|
+
properties: {
|
|
437
|
+
query: { type: 'string', description: 'Query for memory retrieval' },
|
|
438
|
+
k: { type: 'number', description: 'Number of results', default: 12 },
|
|
439
|
+
alpha: { type: 'number', description: 'Similarity weight', default: 0.7 },
|
|
440
|
+
beta: { type: 'number', description: 'Causal uplift weight', default: 0.2 },
|
|
441
|
+
gamma: { type: 'number', description: 'Recency weight', default: 0.1 },
|
|
442
|
+
},
|
|
443
|
+
required: ['query'],
|
|
444
|
+
},
|
|
445
|
+
},
|
|
446
|
+
{
|
|
447
|
+
name: 'learner_discover',
|
|
448
|
+
description: 'Automatically discover causal patterns from episode history',
|
|
449
|
+
inputSchema: {
|
|
450
|
+
type: 'object',
|
|
451
|
+
properties: {
|
|
452
|
+
min_attempts: { type: 'number', description: 'Minimum attempts required', default: 3 },
|
|
453
|
+
min_success_rate: { type: 'number', description: 'Minimum success rate', default: 0.6 },
|
|
454
|
+
min_confidence: { type: 'number', description: 'Minimum statistical confidence', default: 0.7 },
|
|
455
|
+
dry_run: { type: 'boolean', description: 'Preview without storing', default: false },
|
|
456
|
+
},
|
|
457
|
+
},
|
|
458
|
+
},
|
|
459
|
+
{
|
|
460
|
+
name: 'db_stats',
|
|
461
|
+
description: 'Get database statistics showing record counts',
|
|
462
|
+
inputSchema: {
|
|
463
|
+
type: 'object',
|
|
464
|
+
properties: {},
|
|
465
|
+
},
|
|
466
|
+
},
|
|
467
|
+
|
|
468
|
+
// ==========================================================================
|
|
469
|
+
// LEARNING SYSTEM TOOLS (v1.3.0 - Tools 1-5)
|
|
470
|
+
// ==========================================================================
|
|
471
|
+
{
|
|
472
|
+
name: 'learning_start_session',
|
|
473
|
+
description: 'Start a new reinforcement learning session with specified algorithm and configuration. Supports 9 RL algorithms: q-learning, sarsa, dqn, policy-gradient, actor-critic, ppo, decision-transformer, mcts, model-based.',
|
|
474
|
+
inputSchema: {
|
|
475
|
+
type: 'object',
|
|
476
|
+
properties: {
|
|
477
|
+
user_id: { type: 'string', description: 'User identifier for the learning session' },
|
|
478
|
+
session_type: {
|
|
479
|
+
type: 'string',
|
|
480
|
+
description: 'RL algorithm type',
|
|
481
|
+
enum: ['q-learning', 'sarsa', 'dqn', 'policy-gradient', 'actor-critic', 'ppo', 'decision-transformer', 'mcts', 'model-based'],
|
|
482
|
+
},
|
|
483
|
+
config: {
|
|
484
|
+
type: 'object',
|
|
485
|
+
description: 'Learning configuration parameters',
|
|
486
|
+
properties: {
|
|
487
|
+
learning_rate: { type: 'number', description: 'Learning rate (0-1)', default: 0.01 },
|
|
488
|
+
discount_factor: { type: 'number', description: 'Discount factor gamma (0-1)', default: 0.99 },
|
|
489
|
+
exploration_rate: { type: 'number', description: 'Epsilon for epsilon-greedy exploration (0-1)', default: 0.1 },
|
|
490
|
+
batch_size: { type: 'number', description: 'Batch size for training', default: 32 },
|
|
491
|
+
target_update_frequency: { type: 'number', description: 'Update frequency for target network', default: 100 },
|
|
492
|
+
},
|
|
493
|
+
required: ['learning_rate', 'discount_factor'],
|
|
494
|
+
},
|
|
495
|
+
},
|
|
496
|
+
required: ['user_id', 'session_type', 'config'],
|
|
497
|
+
},
|
|
498
|
+
},
|
|
499
|
+
{
|
|
500
|
+
name: 'learning_end_session',
|
|
501
|
+
description: 'End an active learning session and save the final trained policy to the database.',
|
|
502
|
+
inputSchema: {
|
|
503
|
+
type: 'object',
|
|
504
|
+
properties: {
|
|
505
|
+
session_id: { type: 'string', description: 'Session ID to end' },
|
|
506
|
+
},
|
|
507
|
+
required: ['session_id'],
|
|
508
|
+
},
|
|
509
|
+
},
|
|
510
|
+
{
|
|
511
|
+
name: 'learning_predict',
|
|
512
|
+
description: 'Get AI-recommended action for a given state with confidence scores and alternative actions.',
|
|
513
|
+
inputSchema: {
|
|
514
|
+
type: 'object',
|
|
515
|
+
properties: {
|
|
516
|
+
session_id: { type: 'string', description: 'Learning session ID' },
|
|
517
|
+
state: { type: 'string', description: 'Current state description' },
|
|
518
|
+
},
|
|
519
|
+
required: ['session_id', 'state'],
|
|
520
|
+
},
|
|
521
|
+
},
|
|
522
|
+
{
|
|
523
|
+
name: 'learning_feedback',
|
|
524
|
+
description: 'Submit feedback on action quality to train the RL policy. Feedback includes reward signal and outcome state.',
|
|
525
|
+
inputSchema: {
|
|
526
|
+
type: 'object',
|
|
527
|
+
properties: {
|
|
528
|
+
session_id: { type: 'string', description: 'Learning session ID' },
|
|
529
|
+
state: { type: 'string', description: 'State where action was taken' },
|
|
530
|
+
action: { type: 'string', description: 'Action that was executed' },
|
|
531
|
+
reward: { type: 'number', description: 'Reward received (higher is better)' },
|
|
532
|
+
next_state: { type: 'string', description: 'Resulting state after action (optional)' },
|
|
533
|
+
success: { type: 'boolean', description: 'Whether the action was successful' },
|
|
534
|
+
},
|
|
535
|
+
required: ['session_id', 'state', 'action', 'reward', 'success'],
|
|
536
|
+
},
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
name: 'learning_train',
|
|
540
|
+
description: 'Train the RL policy using batch learning with collected experiences. Returns training metrics including loss, average reward, and convergence rate.',
|
|
541
|
+
inputSchema: {
|
|
542
|
+
type: 'object',
|
|
543
|
+
properties: {
|
|
544
|
+
session_id: { type: 'string', description: 'Learning session ID to train' },
|
|
545
|
+
epochs: { type: 'number', description: 'Number of training epochs', default: 50 },
|
|
546
|
+
batch_size: { type: 'number', description: 'Batch size for training', default: 32 },
|
|
547
|
+
learning_rate: { type: 'number', description: 'Learning rate for this training run', default: 0.01 },
|
|
548
|
+
},
|
|
549
|
+
required: ['session_id'],
|
|
550
|
+
},
|
|
551
|
+
},
|
|
552
|
+
|
|
553
|
+
// ==========================================================================
|
|
554
|
+
// LEARNING SYSTEM TOOLS (v1.4.0 - Tools 6-10)
|
|
555
|
+
// ==========================================================================
|
|
556
|
+
{
|
|
557
|
+
name: 'learning_metrics',
|
|
558
|
+
description: 'Get learning performance metrics including success rates, rewards, and policy improvement',
|
|
559
|
+
inputSchema: {
|
|
560
|
+
type: 'object',
|
|
561
|
+
properties: {
|
|
562
|
+
session_id: { type: 'string', description: 'Optional session ID to filter metrics' },
|
|
563
|
+
time_window_days: { type: 'number', description: 'Time window in days for metrics (default: 7)', default: 7 },
|
|
564
|
+
include_trends: { type: 'boolean', description: 'Include trend analysis over time', default: true },
|
|
565
|
+
group_by: { type: 'string', description: 'Group metrics by task/session/skill', enum: ['task', 'session', 'skill'], default: 'task' },
|
|
566
|
+
},
|
|
567
|
+
},
|
|
568
|
+
},
|
|
569
|
+
{
|
|
570
|
+
name: 'learning_transfer',
|
|
571
|
+
description: 'Transfer learning between sessions or tasks, enabling knowledge reuse across different contexts',
|
|
572
|
+
inputSchema: {
|
|
573
|
+
type: 'object',
|
|
574
|
+
properties: {
|
|
575
|
+
source_session: { type: 'string', description: 'Source session ID to transfer from' },
|
|
576
|
+
target_session: { type: 'string', description: 'Target session ID to transfer to' },
|
|
577
|
+
source_task: { type: 'string', description: 'Source task pattern to transfer from' },
|
|
578
|
+
target_task: { type: 'string', description: 'Target task pattern to transfer to' },
|
|
579
|
+
min_similarity: { type: 'number', description: 'Minimum similarity threshold (0-1)', default: 0.7, minimum: 0, maximum: 1 },
|
|
580
|
+
transfer_type: { type: 'string', description: 'Type of transfer', enum: ['episodes', 'skills', 'causal_edges', 'all'], default: 'all' },
|
|
581
|
+
max_transfers: { type: 'number', description: 'Maximum number of items to transfer', default: 10 },
|
|
582
|
+
},
|
|
583
|
+
},
|
|
584
|
+
},
|
|
585
|
+
{
|
|
586
|
+
name: 'learning_explain',
|
|
587
|
+
description: 'Explain action recommendations with confidence scores and supporting evidence from past experiences',
|
|
588
|
+
inputSchema: {
|
|
589
|
+
type: 'object',
|
|
590
|
+
properties: {
|
|
591
|
+
query: { type: 'string', description: 'Query or task description to get recommendations for' },
|
|
592
|
+
k: { type: 'number', description: 'Number of recommendations to return', default: 5 },
|
|
593
|
+
explain_depth: { type: 'string', description: 'Explanation detail level', enum: ['summary', 'detailed', 'full'], default: 'detailed' },
|
|
594
|
+
include_confidence: { type: 'boolean', description: 'Include confidence scores', default: true },
|
|
595
|
+
include_evidence: { type: 'boolean', description: 'Include supporting evidence from past episodes', default: true },
|
|
596
|
+
include_causal: { type: 'boolean', description: 'Include causal reasoning chains', default: true },
|
|
597
|
+
},
|
|
598
|
+
required: ['query'],
|
|
599
|
+
},
|
|
600
|
+
},
|
|
601
|
+
{
|
|
602
|
+
name: 'experience_record',
|
|
603
|
+
description: 'Record tool execution as experience for reinforcement learning and experience replay',
|
|
604
|
+
inputSchema: {
|
|
605
|
+
type: 'object',
|
|
606
|
+
properties: {
|
|
607
|
+
session_id: { type: 'string', description: 'Session identifier' },
|
|
608
|
+
tool_name: { type: 'string', description: 'Name of the tool executed' },
|
|
609
|
+
action: { type: 'string', description: 'Action taken or tool parameters' },
|
|
610
|
+
state_before: { type: 'object', description: 'System state before action (JSON)' },
|
|
611
|
+
state_after: { type: 'object', description: 'System state after action (JSON)' },
|
|
612
|
+
outcome: { type: 'string', description: 'Outcome description' },
|
|
613
|
+
reward: { type: 'number', description: 'Reward signal (0-1)', minimum: 0, maximum: 1 },
|
|
614
|
+
success: { type: 'boolean', description: 'Whether the action succeeded' },
|
|
615
|
+
latency_ms: { type: 'number', description: 'Execution latency in milliseconds' },
|
|
616
|
+
metadata: { type: 'object', description: 'Additional metadata (JSON)' },
|
|
617
|
+
},
|
|
618
|
+
required: ['session_id', 'tool_name', 'action', 'outcome', 'reward', 'success'],
|
|
619
|
+
},
|
|
620
|
+
},
|
|
621
|
+
{
|
|
622
|
+
name: 'reward_signal',
|
|
623
|
+
description: 'Calculate reward signal for outcomes based on success, efficiency, and causal impact',
|
|
624
|
+
inputSchema: {
|
|
625
|
+
type: 'object',
|
|
626
|
+
properties: {
|
|
627
|
+
episode_id: { type: 'number', description: 'Episode ID to calculate reward for' },
|
|
628
|
+
success: { type: 'boolean', description: 'Whether the outcome was successful' },
|
|
629
|
+
target_achieved: { type: 'boolean', description: 'Whether the target was achieved', default: true },
|
|
630
|
+
efficiency_score: { type: 'number', description: 'Efficiency score (0-1)', default: 0.5, minimum: 0, maximum: 1 },
|
|
631
|
+
quality_score: { type: 'number', description: 'Quality score (0-1)', default: 0.5, minimum: 0, maximum: 1 },
|
|
632
|
+
time_taken_ms: { type: 'number', description: 'Time taken in milliseconds' },
|
|
633
|
+
expected_time_ms: { type: 'number', description: 'Expected time in milliseconds' },
|
|
634
|
+
include_causal: { type: 'boolean', description: 'Include causal impact in reward', default: true },
|
|
635
|
+
reward_function: { type: 'string', description: 'Reward function to use', enum: ['standard', 'sparse', 'dense', 'shaped'], default: 'standard' },
|
|
636
|
+
},
|
|
637
|
+
required: ['success'],
|
|
638
|
+
},
|
|
639
|
+
},
|
|
640
|
+
|
|
641
|
+
// ==========================================================================
|
|
642
|
+
// CORE AGENTDB TOOLS (6-10) - v1.3.0
|
|
643
|
+
// ==========================================================================
|
|
644
|
+
{
|
|
645
|
+
name: 'agentdb_stats',
|
|
646
|
+
description: 'Get comprehensive database statistics including table counts, storage usage, and performance metrics',
|
|
647
|
+
inputSchema: {
|
|
648
|
+
type: 'object',
|
|
649
|
+
properties: {
|
|
650
|
+
detailed: { type: 'boolean', description: 'Include detailed statistics', default: false },
|
|
651
|
+
},
|
|
652
|
+
},
|
|
653
|
+
},
|
|
654
|
+
{
|
|
655
|
+
name: 'agentdb_pattern_store',
|
|
656
|
+
description: 'Store reasoning pattern with embedding, taskType, approach, and successRate',
|
|
657
|
+
inputSchema: {
|
|
658
|
+
type: 'object',
|
|
659
|
+
properties: {
|
|
660
|
+
taskType: { type: 'string', description: 'Type of task (e.g., "code_review", "data_analysis")' },
|
|
661
|
+
approach: { type: 'string', description: 'Description of the reasoning approach' },
|
|
662
|
+
successRate: { type: 'number', description: 'Success rate (0-1)', default: 0.0 },
|
|
663
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags' },
|
|
664
|
+
metadata: { type: 'object', description: 'Additional metadata' },
|
|
665
|
+
},
|
|
666
|
+
required: ['taskType', 'approach', 'successRate'],
|
|
667
|
+
},
|
|
668
|
+
},
|
|
669
|
+
{
|
|
670
|
+
name: 'agentdb_pattern_search',
|
|
671
|
+
description: 'Search patterns with taskEmbedding, k, threshold, and filters',
|
|
672
|
+
inputSchema: {
|
|
673
|
+
type: 'object',
|
|
674
|
+
properties: {
|
|
675
|
+
task: { type: 'string', description: 'Task description to search for' },
|
|
676
|
+
k: { type: 'number', description: 'Number of results to return', default: 10 },
|
|
677
|
+
threshold: { type: 'number', description: 'Minimum similarity threshold (0-1)', default: 0.0 },
|
|
678
|
+
filters: {
|
|
679
|
+
type: 'object',
|
|
680
|
+
properties: {
|
|
681
|
+
taskType: { type: 'string', description: 'Filter by task type' },
|
|
682
|
+
minSuccessRate: { type: 'number', description: 'Minimum success rate' },
|
|
683
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },
|
|
684
|
+
},
|
|
685
|
+
description: 'Optional filters',
|
|
686
|
+
},
|
|
687
|
+
},
|
|
688
|
+
required: ['task'],
|
|
689
|
+
},
|
|
690
|
+
},
|
|
691
|
+
{
|
|
692
|
+
name: 'agentdb_pattern_stats',
|
|
693
|
+
description: 'Get pattern statistics including total patterns, success rates, and top task types',
|
|
694
|
+
inputSchema: {
|
|
695
|
+
type: 'object',
|
|
696
|
+
properties: {},
|
|
697
|
+
},
|
|
698
|
+
},
|
|
699
|
+
{
|
|
700
|
+
name: 'agentdb_clear_cache',
|
|
701
|
+
description: 'Clear query cache to refresh statistics and search results',
|
|
702
|
+
inputSchema: {
|
|
703
|
+
type: 'object',
|
|
704
|
+
properties: {
|
|
705
|
+
cache_type: {
|
|
706
|
+
type: 'string',
|
|
707
|
+
description: 'Type of cache to clear (all, patterns, stats)',
|
|
708
|
+
enum: ['all', 'patterns', 'stats'],
|
|
709
|
+
default: 'all'
|
|
710
|
+
},
|
|
711
|
+
},
|
|
712
|
+
},
|
|
713
|
+
},
|
|
714
|
+
];
|
|
715
|
+
|
|
716
|
+
// ============================================================================
|
|
717
|
+
// Tool Handlers
|
|
718
|
+
// ============================================================================
|
|
719
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
720
|
+
return { tools };
|
|
721
|
+
});
|
|
722
|
+
|
|
723
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
724
|
+
const { name, arguments: args } = request.params;
|
|
725
|
+
|
|
726
|
+
try {
|
|
727
|
+
switch (name) {
|
|
728
|
+
// ======================================================================
|
|
729
|
+
// CORE VECTOR DB OPERATIONS
|
|
730
|
+
// ======================================================================
|
|
731
|
+
case 'agentdb_init': {
|
|
732
|
+
const targetDbPath = (args?.db_path as string) || dbPath;
|
|
733
|
+
|
|
734
|
+
if (args?.reset && fs.existsSync(targetDbPath)) {
|
|
735
|
+
fs.unlinkSync(targetDbPath);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// Initialize schema
|
|
739
|
+
initializeSchema();
|
|
740
|
+
|
|
741
|
+
const stats = db.prepare('SELECT COUNT(*) as count FROM sqlite_master WHERE type="table"').get() as any;
|
|
742
|
+
|
|
743
|
+
return {
|
|
744
|
+
content: [
|
|
745
|
+
{
|
|
746
|
+
type: 'text',
|
|
747
|
+
text: `ā
AgentDB initialized successfully!\n` +
|
|
748
|
+
`š Database: ${targetDbPath}\n` +
|
|
749
|
+
`š Tables created: ${stats.count}\n` +
|
|
750
|
+
`āļø Optimizations: WAL mode, cache_size=64MB\n` +
|
|
751
|
+
`š§ Embedding service: ${embeddingService.constructor.name} ready`,
|
|
752
|
+
},
|
|
753
|
+
],
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
case 'agentdb_insert': {
|
|
758
|
+
const text = args?.text as string;
|
|
759
|
+
const sessionId = (args?.session_id as string) || 'default';
|
|
760
|
+
const tags = (args?.tags as string[]) || [];
|
|
761
|
+
const metadata = (args?.metadata as Record<string, any>) || {};
|
|
762
|
+
|
|
763
|
+
const episodeId = await reflexion.storeEpisode({
|
|
764
|
+
sessionId,
|
|
765
|
+
task: text,
|
|
766
|
+
reward: 1.0,
|
|
767
|
+
success: true,
|
|
768
|
+
input: text,
|
|
769
|
+
output: '',
|
|
770
|
+
critique: '',
|
|
771
|
+
latencyMs: 0,
|
|
772
|
+
tokensUsed: 0,
|
|
773
|
+
tags,
|
|
774
|
+
metadata,
|
|
775
|
+
});
|
|
776
|
+
|
|
777
|
+
return {
|
|
778
|
+
content: [
|
|
779
|
+
{
|
|
780
|
+
type: 'text',
|
|
781
|
+
text: `ā
Vector inserted successfully!\n` +
|
|
782
|
+
`š ID: ${episodeId}\n` +
|
|
783
|
+
`š Text: ${text.substring(0, 100)}${text.length > 100 ? '...' : ''}\n` +
|
|
784
|
+
`š·ļø Tags: ${tags.join(', ') || 'none'}\n` +
|
|
785
|
+
`š§ Embedding: ${embeddingService.constructor.name}`,
|
|
786
|
+
},
|
|
787
|
+
],
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
case 'agentdb_insert_batch': {
|
|
792
|
+
const items = (args?.items as any[]) || [];
|
|
793
|
+
const batchSize = (args?.batch_size as number) || 100;
|
|
794
|
+
|
|
795
|
+
const episodes = items.map((item: any) => ({
|
|
796
|
+
sessionId: item.session_id || 'default',
|
|
797
|
+
task: item.text,
|
|
798
|
+
reward: 1.0,
|
|
799
|
+
success: true,
|
|
800
|
+
input: item.text,
|
|
801
|
+
output: '',
|
|
802
|
+
critique: '',
|
|
803
|
+
latencyMs: 0,
|
|
804
|
+
tokensUsed: 0,
|
|
805
|
+
tags: item.tags || [],
|
|
806
|
+
metadata: item.metadata || {},
|
|
807
|
+
}));
|
|
808
|
+
|
|
809
|
+
const batchOpsConfig = new BatchOperations(db, embeddingService, {
|
|
810
|
+
batchSize,
|
|
811
|
+
parallelism: 4,
|
|
812
|
+
});
|
|
813
|
+
|
|
814
|
+
const inserted = await batchOpsConfig.insertEpisodes(episodes);
|
|
815
|
+
|
|
816
|
+
return {
|
|
817
|
+
content: [
|
|
818
|
+
{
|
|
819
|
+
type: 'text',
|
|
820
|
+
text: `ā
Batch insert completed!\n` +
|
|
821
|
+
`š Inserted: ${inserted} vectors\n` +
|
|
822
|
+
`ā” Batch size: ${batchSize}\n` +
|
|
823
|
+
`š§ Embeddings generated in parallel\n` +
|
|
824
|
+
`š¾ Transaction committed`,
|
|
825
|
+
},
|
|
826
|
+
],
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
case 'agentdb_search': {
|
|
831
|
+
const queryText = args?.query as string;
|
|
832
|
+
const k = (args?.k as number) || 10;
|
|
833
|
+
const minSimilarity = (args?.min_similarity as number) || 0.0;
|
|
834
|
+
const filters = args?.filters as any;
|
|
835
|
+
|
|
836
|
+
const query: any = {
|
|
837
|
+
task: queryText,
|
|
838
|
+
k,
|
|
839
|
+
};
|
|
840
|
+
|
|
841
|
+
if (filters) {
|
|
842
|
+
if (filters.min_reward !== undefined) {
|
|
843
|
+
query.minReward = filters.min_reward;
|
|
844
|
+
}
|
|
845
|
+
// Session ID filter would require custom query
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
const results = await reflexion.retrieveRelevant(query);
|
|
849
|
+
|
|
850
|
+
// Filter by minimum similarity if specified
|
|
851
|
+
let filteredResults = results;
|
|
852
|
+
if (minSimilarity > 0) {
|
|
853
|
+
filteredResults = results.filter(r => (r.similarity || 0) >= minSimilarity);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
return {
|
|
857
|
+
content: [
|
|
858
|
+
{
|
|
859
|
+
type: 'text',
|
|
860
|
+
text: `š Search completed!\n` +
|
|
861
|
+
`š Found: ${filteredResults.length} results\n` +
|
|
862
|
+
`šÆ Query: ${queryText}\n\n` +
|
|
863
|
+
`Top Results:\n` +
|
|
864
|
+
filteredResults.slice(0, 5).map((r, i) =>
|
|
865
|
+
`${i + 1}. [ID: ${r.id}] Similarity: ${(r.similarity || 0).toFixed(3)}\n` +
|
|
866
|
+
` Task: ${r.task.substring(0, 80)}${r.task.length > 80 ? '...' : ''}\n` +
|
|
867
|
+
` Reward: ${r.reward.toFixed(2)}`
|
|
868
|
+
).join('\n\n') +
|
|
869
|
+
(filteredResults.length > 5 ? `\n\n... and ${filteredResults.length - 5} more results` : ''),
|
|
870
|
+
},
|
|
871
|
+
],
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
case 'agentdb_delete': {
|
|
876
|
+
let deleted = 0;
|
|
877
|
+
const id = args?.id as number | undefined;
|
|
878
|
+
const filters = args?.filters as any;
|
|
879
|
+
|
|
880
|
+
if (id !== undefined) {
|
|
881
|
+
// Delete single vector
|
|
882
|
+
const stmt = db.prepare('DELETE FROM episodes WHERE id = ?');
|
|
883
|
+
const result = stmt.run(id);
|
|
884
|
+
deleted = result.changes;
|
|
885
|
+
} else if (filters) {
|
|
886
|
+
// Bulk delete with filters
|
|
887
|
+
const conditions: Record<string, any> = {};
|
|
888
|
+
|
|
889
|
+
if (filters.session_id) {
|
|
890
|
+
conditions.session_id = filters.session_id;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
if (filters.before_timestamp) {
|
|
894
|
+
const stmt = db.prepare('DELETE FROM episodes WHERE ts < ?');
|
|
895
|
+
const result = stmt.run(filters.before_timestamp);
|
|
896
|
+
deleted = result.changes;
|
|
897
|
+
} else if (Object.keys(conditions).length > 0) {
|
|
898
|
+
deleted = batchOps.bulkDelete('episodes', conditions);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
return {
|
|
903
|
+
content: [
|
|
904
|
+
{
|
|
905
|
+
type: 'text',
|
|
906
|
+
text: `ā
Delete operation completed!\n` +
|
|
907
|
+
`š Deleted: ${deleted} vector(s)\n` +
|
|
908
|
+
`šļø ${id !== undefined ? `ID: ${id}` : 'Bulk deletion with filters'}`,
|
|
909
|
+
},
|
|
910
|
+
],
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// ======================================================================
|
|
915
|
+
// FRONTIER MEMORY FEATURES (EXISTING)
|
|
916
|
+
// ======================================================================
|
|
917
|
+
case 'reflexion_store': {
|
|
918
|
+
const episodeId = await reflexion.storeEpisode({
|
|
919
|
+
sessionId: args?.session_id as string,
|
|
920
|
+
task: args?.task as string,
|
|
921
|
+
reward: args?.reward as number,
|
|
922
|
+
success: args?.success as boolean,
|
|
923
|
+
critique: (args?.critique as string) || '',
|
|
924
|
+
input: (args?.input as string) || '',
|
|
925
|
+
output: (args?.output as string) || '',
|
|
926
|
+
latencyMs: (args?.latency_ms as number) || 0,
|
|
927
|
+
tokensUsed: (args?.tokens as number) || 0,
|
|
928
|
+
});
|
|
929
|
+
return {
|
|
930
|
+
content: [
|
|
931
|
+
{
|
|
932
|
+
type: 'text',
|
|
933
|
+
text: `ā
Stored episode #${episodeId}\nTask: ${args?.task}\nReward: ${args?.reward}\nSuccess: ${args?.success}`,
|
|
934
|
+
},
|
|
935
|
+
],
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
case 'reflexion_retrieve': {
|
|
940
|
+
const episodes = await reflexion.retrieveRelevant({
|
|
941
|
+
task: args?.task as string,
|
|
942
|
+
k: (args?.k as number) || 5,
|
|
943
|
+
onlyFailures: args?.only_failures as boolean | undefined,
|
|
944
|
+
onlySuccesses: args?.only_successes as boolean | undefined,
|
|
945
|
+
minReward: args?.min_reward as number | undefined,
|
|
946
|
+
});
|
|
947
|
+
return {
|
|
948
|
+
content: [
|
|
949
|
+
{
|
|
950
|
+
type: 'text',
|
|
951
|
+
text: `š Retrieved ${episodes.length} episodes:\n\n` +
|
|
952
|
+
episodes.map((ep, i) =>
|
|
953
|
+
`${i + 1}. Episode ${ep.id}\n Task: ${ep.task}\n Reward: ${ep.reward.toFixed(2)}\n Similarity: ${ep.similarity?.toFixed(3) || 'N/A'}`
|
|
954
|
+
).join('\n\n'),
|
|
955
|
+
},
|
|
956
|
+
],
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
case 'skill_create': {
|
|
961
|
+
const skillId = await skills.createSkill({
|
|
962
|
+
name: args?.name as string,
|
|
963
|
+
description: args?.description as string,
|
|
964
|
+
signature: { inputs: {}, outputs: {} },
|
|
965
|
+
code: (args?.code as string) || '',
|
|
966
|
+
successRate: (args?.success_rate as number) || 0.0,
|
|
967
|
+
uses: 0,
|
|
968
|
+
avgReward: 0.0,
|
|
969
|
+
avgLatencyMs: 0.0,
|
|
970
|
+
});
|
|
971
|
+
return {
|
|
972
|
+
content: [
|
|
973
|
+
{
|
|
974
|
+
type: 'text',
|
|
975
|
+
text: `ā
Created skill #${skillId}: ${args?.name}`,
|
|
976
|
+
},
|
|
977
|
+
],
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
case 'skill_search': {
|
|
982
|
+
const foundSkills = await skills.searchSkills({
|
|
983
|
+
task: args?.task as string,
|
|
984
|
+
k: (args?.k as number) || 10,
|
|
985
|
+
minSuccessRate: (args?.min_success_rate as number) || 0.0,
|
|
986
|
+
});
|
|
987
|
+
return {
|
|
988
|
+
content: [
|
|
989
|
+
{
|
|
990
|
+
type: 'text',
|
|
991
|
+
text: `š Found ${foundSkills.length} skills:\n\n` +
|
|
992
|
+
foundSkills.map((skill, i) =>
|
|
993
|
+
`${i + 1}. ${skill.name}\n ${skill.description}\n Success: ${(skill.successRate * 100).toFixed(1)}%`
|
|
994
|
+
).join('\n\n'),
|
|
995
|
+
},
|
|
996
|
+
],
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
case 'causal_add_edge': {
|
|
1001
|
+
const cause = args?.cause as string;
|
|
1002
|
+
const effect = args?.effect as string;
|
|
1003
|
+
const uplift = args?.uplift as number;
|
|
1004
|
+
const confidence = (args?.confidence as number) || 0.95;
|
|
1005
|
+
const sampleSize = (args?.sample_size as number) || 0;
|
|
1006
|
+
|
|
1007
|
+
const edgeId = causalGraph.addCausalEdge({
|
|
1008
|
+
fromMemoryId: 0,
|
|
1009
|
+
fromMemoryType: cause as 'episode' | 'skill' | 'note' | 'fact',
|
|
1010
|
+
toMemoryId: 0,
|
|
1011
|
+
toMemoryType: effect as 'episode' | 'skill' | 'note' | 'fact',
|
|
1012
|
+
similarity: 0,
|
|
1013
|
+
uplift,
|
|
1014
|
+
confidence,
|
|
1015
|
+
sampleSize,
|
|
1016
|
+
evidenceIds: [],
|
|
1017
|
+
});
|
|
1018
|
+
return {
|
|
1019
|
+
content: [
|
|
1020
|
+
{
|
|
1021
|
+
type: 'text',
|
|
1022
|
+
text: `ā
Added causal edge #${edgeId}\n${cause} ā ${effect}\nUplift: ${uplift}`,
|
|
1023
|
+
},
|
|
1024
|
+
],
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
case 'causal_query': {
|
|
1029
|
+
const cause = args?.cause as string | undefined;
|
|
1030
|
+
const effect = args?.effect as string | undefined;
|
|
1031
|
+
const minConfidence = (args?.min_confidence as number) || 0.5;
|
|
1032
|
+
const minUplift = (args?.min_uplift as number) || 0.0;
|
|
1033
|
+
const limit = (args?.limit as number) || 10;
|
|
1034
|
+
|
|
1035
|
+
const edges = causalGraph.queryCausalEffects({
|
|
1036
|
+
interventionMemoryId: 0,
|
|
1037
|
+
interventionMemoryType: cause || '',
|
|
1038
|
+
outcomeMemoryId: effect ? 0 : undefined,
|
|
1039
|
+
minConfidence,
|
|
1040
|
+
minUplift,
|
|
1041
|
+
});
|
|
1042
|
+
const limited = edges.slice(0, limit);
|
|
1043
|
+
return {
|
|
1044
|
+
content: [
|
|
1045
|
+
{
|
|
1046
|
+
type: 'text',
|
|
1047
|
+
text: `š Found ${edges.length} causal edges:\n\n` +
|
|
1048
|
+
limited.map((edge, i) =>
|
|
1049
|
+
`${i + 1}. ${edge.fromMemoryType} ā ${edge.toMemoryType}\n Uplift: ${(edge.uplift || 0).toFixed(3)} (confidence: ${edge.confidence.toFixed(2)})`
|
|
1050
|
+
).join('\n\n'),
|
|
1051
|
+
},
|
|
1052
|
+
],
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
case 'recall_with_certificate': {
|
|
1057
|
+
const query = args?.query as string;
|
|
1058
|
+
const k = (args?.k as number) || 12;
|
|
1059
|
+
|
|
1060
|
+
const result = await causalRecall.recall(
|
|
1061
|
+
'mcp-' + Date.now(),
|
|
1062
|
+
query,
|
|
1063
|
+
k,
|
|
1064
|
+
undefined,
|
|
1065
|
+
'internal'
|
|
1066
|
+
);
|
|
1067
|
+
return {
|
|
1068
|
+
content: [
|
|
1069
|
+
{
|
|
1070
|
+
type: 'text',
|
|
1071
|
+
text: `š Retrieved ${result.candidates.length} results:\n\n` +
|
|
1072
|
+
result.candidates.slice(0, 5).map((r, i) =>
|
|
1073
|
+
`${i + 1}. ${r.type} ${r.id}\n Similarity: ${r.similarity.toFixed(3)}\n Uplift: ${r.uplift?.toFixed(3) || '0.000'}`
|
|
1074
|
+
).join('\n\n') +
|
|
1075
|
+
`\n\nš Certificate ID: ${result.certificate.id}`,
|
|
1076
|
+
},
|
|
1077
|
+
],
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
case 'learner_discover': {
|
|
1082
|
+
const minAttempts = (args?.min_attempts as number) || 3;
|
|
1083
|
+
const minSuccessRate = (args?.min_success_rate as number) || 0.6;
|
|
1084
|
+
const minConfidence = (args?.min_confidence as number) || 0.7;
|
|
1085
|
+
const dryRun = (args?.dry_run as boolean) || false;
|
|
1086
|
+
|
|
1087
|
+
const discovered = await learner.discover({
|
|
1088
|
+
minAttempts,
|
|
1089
|
+
minSuccessRate,
|
|
1090
|
+
minConfidence,
|
|
1091
|
+
dryRun,
|
|
1092
|
+
});
|
|
1093
|
+
return {
|
|
1094
|
+
content: [
|
|
1095
|
+
{
|
|
1096
|
+
type: 'text',
|
|
1097
|
+
text: `š Discovered ${discovered.length} causal patterns:\n\n` +
|
|
1098
|
+
discovered.slice(0, 10).map((edge, i) =>
|
|
1099
|
+
`${i + 1}. ${edge.fromMemoryType} ā ${edge.toMemoryType}\n Uplift: ${(edge.uplift || 0).toFixed(3)} (n=${edge.sampleSize || 0})`
|
|
1100
|
+
).join('\n\n'),
|
|
1101
|
+
},
|
|
1102
|
+
],
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
case 'db_stats': {
|
|
1107
|
+
const stats: Record<string, number> = {
|
|
1108
|
+
causal_edges: (db.prepare('SELECT COUNT(*) as count FROM causal_edges').get() as any)?.count || 0,
|
|
1109
|
+
causal_experiments: (db.prepare('SELECT COUNT(*) as count FROM causal_experiments').get() as any)?.count || 0,
|
|
1110
|
+
causal_observations: (db.prepare('SELECT COUNT(*) as count FROM causal_observations').get() as any)?.count || 0,
|
|
1111
|
+
episodes: (db.prepare('SELECT COUNT(*) as count FROM episodes').get() as any)?.count || 0,
|
|
1112
|
+
episode_embeddings: (db.prepare('SELECT COUNT(*) as count FROM episode_embeddings').get() as any)?.count || 0,
|
|
1113
|
+
skills: (db.prepare('SELECT COUNT(*) as count FROM skills').get() as any)?.count || 0,
|
|
1114
|
+
};
|
|
1115
|
+
return {
|
|
1116
|
+
content: [
|
|
1117
|
+
{
|
|
1118
|
+
type: 'text',
|
|
1119
|
+
text: `š Database Statistics:\n\n` +
|
|
1120
|
+
`Causal Edges: ${stats.causal_edges}\n` +
|
|
1121
|
+
`Experiments: ${stats.causal_experiments}\n` +
|
|
1122
|
+
`Observations: ${stats.causal_observations}\n` +
|
|
1123
|
+
`Episodes (Vectors): ${stats.episodes}\n` +
|
|
1124
|
+
`Episode Embeddings: ${stats.episode_embeddings}\n` +
|
|
1125
|
+
`Skills: ${stats.skills}`,
|
|
1126
|
+
},
|
|
1127
|
+
],
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// ======================================================================
|
|
1132
|
+
// CORE AGENTDB TOOLS (6-10)
|
|
1133
|
+
// ======================================================================
|
|
1134
|
+
case 'agentdb_stats': {
|
|
1135
|
+
const detailed = (args?.detailed as boolean) || false;
|
|
1136
|
+
|
|
1137
|
+
const stats: Record<string, number> = {
|
|
1138
|
+
causal_edges: (db.prepare('SELECT COUNT(*) as count FROM causal_edges').get() as any)?.count || 0,
|
|
1139
|
+
causal_experiments: (db.prepare('SELECT COUNT(*) as count FROM causal_experiments').get() as any)?.count || 0,
|
|
1140
|
+
causal_observations: (db.prepare('SELECT COUNT(*) as count FROM causal_observations').get() as any)?.count || 0,
|
|
1141
|
+
episodes: (db.prepare('SELECT COUNT(*) as count FROM episodes').get() as any)?.count || 0,
|
|
1142
|
+
episode_embeddings: (db.prepare('SELECT COUNT(*) as count FROM episode_embeddings').get() as any)?.count || 0,
|
|
1143
|
+
skills: (db.prepare('SELECT COUNT(*) as count FROM skills').get() as any)?.count || 0,
|
|
1144
|
+
skill_embeddings: (db.prepare('SELECT COUNT(*) as count FROM skill_embeddings').get() as any)?.count || 0,
|
|
1145
|
+
reasoning_patterns: (db.prepare('SELECT COUNT(*) as count FROM reasoning_patterns').get() as any)?.count || 0,
|
|
1146
|
+
pattern_embeddings: (db.prepare('SELECT COUNT(*) as count FROM pattern_embeddings').get() as any)?.count || 0,
|
|
1147
|
+
learning_sessions: (db.prepare('SELECT COUNT(*) as count FROM rl_sessions').get() as any)?.count || 0,
|
|
1148
|
+
};
|
|
1149
|
+
|
|
1150
|
+
let output = `š AgentDB Comprehensive Statistics\n\n` +
|
|
1151
|
+
`š§ Memory & Learning:\n` +
|
|
1152
|
+
` Episodes (Vectors): ${stats.episodes}\n` +
|
|
1153
|
+
` Episode Embeddings: ${stats.episode_embeddings}\n` +
|
|
1154
|
+
` Skills: ${stats.skills}\n` +
|
|
1155
|
+
` Skill Embeddings: ${stats.skill_embeddings}\n` +
|
|
1156
|
+
` Reasoning Patterns: ${stats.reasoning_patterns}\n` +
|
|
1157
|
+
` Pattern Embeddings: ${stats.pattern_embeddings}\n` +
|
|
1158
|
+
` Learning Sessions: ${stats.learning_sessions}\n\n` +
|
|
1159
|
+
`š Causal Intelligence:\n` +
|
|
1160
|
+
` Causal Edges: ${stats.causal_edges}\n` +
|
|
1161
|
+
` Experiments: ${stats.causal_experiments}\n` +
|
|
1162
|
+
` Observations: ${stats.causal_observations}\n`;
|
|
1163
|
+
|
|
1164
|
+
if (detailed) {
|
|
1165
|
+
// Add storage statistics
|
|
1166
|
+
const dbStats = db.prepare(`
|
|
1167
|
+
SELECT page_count * page_size as total_bytes
|
|
1168
|
+
FROM pragma_page_count(), pragma_page_size()
|
|
1169
|
+
`).get() as any;
|
|
1170
|
+
|
|
1171
|
+
const totalMB = (dbStats.total_bytes / (1024 * 1024)).toFixed(2);
|
|
1172
|
+
|
|
1173
|
+
// Add recent activity stats
|
|
1174
|
+
const recentActivity = db.prepare(`
|
|
1175
|
+
SELECT COUNT(*) as count
|
|
1176
|
+
FROM episodes
|
|
1177
|
+
WHERE ts >= strftime('%s', 'now', '-7 days')
|
|
1178
|
+
`).get() as any;
|
|
1179
|
+
|
|
1180
|
+
output += `\nš¦ Storage:\n` +
|
|
1181
|
+
` Database Size: ${totalMB} MB\n` +
|
|
1182
|
+
` Recent Activity (7d): ${recentActivity.count} episodes\n`;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
return {
|
|
1186
|
+
content: [
|
|
1187
|
+
{
|
|
1188
|
+
type: 'text',
|
|
1189
|
+
text: output,
|
|
1190
|
+
},
|
|
1191
|
+
],
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
case 'agentdb_pattern_store': {
|
|
1196
|
+
const taskType = args?.taskType as string;
|
|
1197
|
+
const approach = args?.approach as string;
|
|
1198
|
+
const successRate = args?.successRate as number;
|
|
1199
|
+
const tags = (args?.tags as string[]) || [];
|
|
1200
|
+
const metadata = (args?.metadata as Record<string, any>) || {};
|
|
1201
|
+
|
|
1202
|
+
const patternId = await reasoningBank.storePattern({
|
|
1203
|
+
taskType,
|
|
1204
|
+
approach,
|
|
1205
|
+
successRate,
|
|
1206
|
+
tags,
|
|
1207
|
+
metadata,
|
|
1208
|
+
});
|
|
1209
|
+
|
|
1210
|
+
return {
|
|
1211
|
+
content: [
|
|
1212
|
+
{
|
|
1213
|
+
type: 'text',
|
|
1214
|
+
text: `ā
Reasoning pattern stored successfully!\n\n` +
|
|
1215
|
+
`š Pattern ID: ${patternId}\n` +
|
|
1216
|
+
`š Task Type: ${taskType}\n` +
|
|
1217
|
+
`š” Approach: ${approach.substring(0, 100)}${approach.length > 100 ? '...' : ''}\n` +
|
|
1218
|
+
`š Success Rate: ${(successRate * 100).toFixed(1)}%\n` +
|
|
1219
|
+
`š·ļø Tags: ${tags.join(', ') || 'none'}\n` +
|
|
1220
|
+
`š§ Embedding generated and stored`,
|
|
1221
|
+
},
|
|
1222
|
+
],
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
case 'agentdb_pattern_search': {
|
|
1227
|
+
const task = args?.task as string;
|
|
1228
|
+
const k = (args?.k as number) || 10;
|
|
1229
|
+
const threshold = (args?.threshold as number) || 0.0;
|
|
1230
|
+
const filters = args?.filters as any;
|
|
1231
|
+
|
|
1232
|
+
// Generate embedding for the task
|
|
1233
|
+
const taskEmbedding = await embeddingService.embed(task);
|
|
1234
|
+
|
|
1235
|
+
const patterns = await reasoningBank.searchPatterns({
|
|
1236
|
+
taskEmbedding,
|
|
1237
|
+
k,
|
|
1238
|
+
threshold,
|
|
1239
|
+
filters: filters ? {
|
|
1240
|
+
taskType: filters.taskType,
|
|
1241
|
+
minSuccessRate: filters.minSuccessRate,
|
|
1242
|
+
tags: filters.tags,
|
|
1243
|
+
} : undefined,
|
|
1244
|
+
});
|
|
1245
|
+
|
|
1246
|
+
return {
|
|
1247
|
+
content: [
|
|
1248
|
+
{
|
|
1249
|
+
type: 'text',
|
|
1250
|
+
text: `š Pattern search completed!\n\n` +
|
|
1251
|
+
`š Found: ${patterns.length} matching patterns\n` +
|
|
1252
|
+
`šÆ Query: ${task}\n` +
|
|
1253
|
+
`šļø Threshold: ${threshold.toFixed(2)}\n\n` +
|
|
1254
|
+
`Top Results:\n` +
|
|
1255
|
+
patterns.slice(0, 5).map((p, i) =>
|
|
1256
|
+
`${i + 1}. [ID: ${p.id}] ${p.taskType}\n` +
|
|
1257
|
+
` Similarity: ${(p.similarity || 0).toFixed(3)}\n` +
|
|
1258
|
+
` Success Rate: ${(p.successRate * 100).toFixed(1)}%\n` +
|
|
1259
|
+
` Approach: ${p.approach.substring(0, 80)}${p.approach.length > 80 ? '...' : ''}\n` +
|
|
1260
|
+
` Uses: ${p.uses || 0}`
|
|
1261
|
+
).join('\n\n') +
|
|
1262
|
+
(patterns.length > 5 ? `\n\n... and ${patterns.length - 5} more patterns` : ''),
|
|
1263
|
+
},
|
|
1264
|
+
],
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
case 'agentdb_pattern_stats': {
|
|
1269
|
+
const stats = reasoningBank.getPatternStats();
|
|
1270
|
+
|
|
1271
|
+
return {
|
|
1272
|
+
content: [
|
|
1273
|
+
{
|
|
1274
|
+
type: 'text',
|
|
1275
|
+
text: `š Reasoning Pattern Statistics\n\n` +
|
|
1276
|
+
`š Overview:\n` +
|
|
1277
|
+
` Total Patterns: ${stats.totalPatterns}\n` +
|
|
1278
|
+
` Avg Success Rate: ${(stats.avgSuccessRate * 100).toFixed(1)}%\n` +
|
|
1279
|
+
` Avg Uses per Pattern: ${stats.avgUses.toFixed(1)}\n` +
|
|
1280
|
+
` High Performing (ā„80%): ${stats.highPerformingPatterns}\n` +
|
|
1281
|
+
` Recent (7 days): ${stats.recentPatterns}\n\n` +
|
|
1282
|
+
`š Top Task Types:\n` +
|
|
1283
|
+
stats.topTaskTypes.slice(0, 10).map((tt, i) =>
|
|
1284
|
+
` ${i + 1}. ${tt.taskType}: ${tt.count} patterns`
|
|
1285
|
+
).join('\n') +
|
|
1286
|
+
(stats.topTaskTypes.length === 0 ? ' No patterns stored yet' : ''),
|
|
1287
|
+
},
|
|
1288
|
+
],
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
case 'agentdb_clear_cache': {
|
|
1293
|
+
const cacheType = (args?.cache_type as string) || 'all';
|
|
1294
|
+
|
|
1295
|
+
switch (cacheType) {
|
|
1296
|
+
case 'patterns':
|
|
1297
|
+
case 'stats':
|
|
1298
|
+
case 'all':
|
|
1299
|
+
reasoningBank.clearCache();
|
|
1300
|
+
break;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
return {
|
|
1304
|
+
content: [
|
|
1305
|
+
{
|
|
1306
|
+
type: 'text',
|
|
1307
|
+
text: `ā
Cache cleared successfully!\n\n` +
|
|
1308
|
+
`š§¹ Cache Type: ${cacheType}\n` +
|
|
1309
|
+
`ā»ļø Statistics and search results will be refreshed on next query`,
|
|
1310
|
+
},
|
|
1311
|
+
],
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
// ======================================================================
|
|
1316
|
+
// LEARNING SYSTEM TOOLS (Tools 1-5)
|
|
1317
|
+
// ======================================================================
|
|
1318
|
+
case 'learning_start_session': {
|
|
1319
|
+
const userId = args?.user_id as string;
|
|
1320
|
+
const sessionType = args?.session_type as any;
|
|
1321
|
+
const config = args?.config as any;
|
|
1322
|
+
|
|
1323
|
+
const sessionId = await learningSystem.startSession(
|
|
1324
|
+
userId,
|
|
1325
|
+
sessionType,
|
|
1326
|
+
{
|
|
1327
|
+
learningRate: config.learning_rate,
|
|
1328
|
+
discountFactor: config.discount_factor,
|
|
1329
|
+
explorationRate: config.exploration_rate,
|
|
1330
|
+
batchSize: config.batch_size,
|
|
1331
|
+
targetUpdateFrequency: config.target_update_frequency,
|
|
1332
|
+
}
|
|
1333
|
+
);
|
|
1334
|
+
|
|
1335
|
+
return {
|
|
1336
|
+
content: [
|
|
1337
|
+
{
|
|
1338
|
+
type: 'text',
|
|
1339
|
+
text: `ā
Learning session started!\n\n` +
|
|
1340
|
+
`š Session ID: ${sessionId}\n` +
|
|
1341
|
+
`š¤ User: ${userId}\n` +
|
|
1342
|
+
`š§ Algorithm: ${sessionType}\n` +
|
|
1343
|
+
`āļø Config:\n` +
|
|
1344
|
+
` ⢠Learning Rate: ${config.learning_rate}\n` +
|
|
1345
|
+
` ⢠Discount Factor: ${config.discount_factor}\n` +
|
|
1346
|
+
` ⢠Exploration Rate: ${config.exploration_rate || 0.1}\n` +
|
|
1347
|
+
` ⢠Batch Size: ${config.batch_size || 32}\n\n` +
|
|
1348
|
+
`š Use this session ID for predictions and feedback.`,
|
|
1349
|
+
},
|
|
1350
|
+
],
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
case 'learning_end_session': {
|
|
1355
|
+
const sessionId = args?.session_id as string;
|
|
1356
|
+
await learningSystem.endSession(sessionId);
|
|
1357
|
+
|
|
1358
|
+
return {
|
|
1359
|
+
content: [
|
|
1360
|
+
{
|
|
1361
|
+
type: 'text',
|
|
1362
|
+
text: `ā
Learning session ended!\n\n` +
|
|
1363
|
+
`š Session ID: ${sessionId}\n` +
|
|
1364
|
+
`š¾ Final policy saved to database\n` +
|
|
1365
|
+
`š Session marked as completed`,
|
|
1366
|
+
},
|
|
1367
|
+
],
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
case 'learning_predict': {
|
|
1372
|
+
const sessionId = args?.session_id as string;
|
|
1373
|
+
const state = args?.state as string;
|
|
1374
|
+
|
|
1375
|
+
const prediction = await learningSystem.predict(sessionId, state);
|
|
1376
|
+
|
|
1377
|
+
return {
|
|
1378
|
+
content: [
|
|
1379
|
+
{
|
|
1380
|
+
type: 'text',
|
|
1381
|
+
text: `šÆ AI Recommendation:\n\n` +
|
|
1382
|
+
`š State: ${state}\n` +
|
|
1383
|
+
`⨠Recommended Action: ${prediction.action}\n` +
|
|
1384
|
+
`šÆ Confidence: ${(prediction.confidence * 100).toFixed(1)}%\n` +
|
|
1385
|
+
`š Q-Value: ${prediction.qValue?.toFixed(3) || 'N/A'}\n\n` +
|
|
1386
|
+
`š Alternative Actions:\n` +
|
|
1387
|
+
prediction.alternatives.map((alt, i) =>
|
|
1388
|
+
` ${i + 1}. ${alt.action} (${(alt.confidence * 100).toFixed(1)}% confidence)`
|
|
1389
|
+
).join('\n'),
|
|
1390
|
+
},
|
|
1391
|
+
],
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
case 'learning_feedback': {
|
|
1396
|
+
const sessionId = args?.session_id as string;
|
|
1397
|
+
const state = args?.state as string;
|
|
1398
|
+
const action = args?.action as string;
|
|
1399
|
+
const reward = args?.reward as number;
|
|
1400
|
+
const nextState = args?.next_state as string | undefined;
|
|
1401
|
+
const success = args?.success as boolean;
|
|
1402
|
+
|
|
1403
|
+
await learningSystem.submitFeedback({
|
|
1404
|
+
sessionId,
|
|
1405
|
+
state,
|
|
1406
|
+
action,
|
|
1407
|
+
reward,
|
|
1408
|
+
nextState,
|
|
1409
|
+
success,
|
|
1410
|
+
timestamp: Date.now(),
|
|
1411
|
+
});
|
|
1412
|
+
|
|
1413
|
+
return {
|
|
1414
|
+
content: [
|
|
1415
|
+
{
|
|
1416
|
+
type: 'text',
|
|
1417
|
+
text: `ā
Feedback recorded!\n\n` +
|
|
1418
|
+
`š Session: ${sessionId}\n` +
|
|
1419
|
+
`š State: ${state}\n` +
|
|
1420
|
+
`š¬ Action: ${action}\n` +
|
|
1421
|
+
`š Reward: ${reward.toFixed(2)}\n` +
|
|
1422
|
+
`${success ? 'ā
' : 'ā'} Success: ${success}\n` +
|
|
1423
|
+
`${nextState ? `ā”ļø Next State: ${nextState}\n` : ''}` +
|
|
1424
|
+
`š§ Policy updated incrementally`,
|
|
1425
|
+
},
|
|
1426
|
+
],
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
case 'learning_train': {
|
|
1431
|
+
const sessionId = args?.session_id as string;
|
|
1432
|
+
const epochs = (args?.epochs as number) || 50;
|
|
1433
|
+
const batchSize = (args?.batch_size as number) || 32;
|
|
1434
|
+
const learningRate = (args?.learning_rate as number) || 0.01;
|
|
1435
|
+
|
|
1436
|
+
console.log(`š Training session ${sessionId}...`);
|
|
1437
|
+
const result = await learningSystem.train(sessionId, epochs, batchSize, learningRate);
|
|
1438
|
+
|
|
1439
|
+
return {
|
|
1440
|
+
content: [
|
|
1441
|
+
{
|
|
1442
|
+
type: 'text',
|
|
1443
|
+
text: `š Training completed!\n\n` +
|
|
1444
|
+
`š Training Results:\n` +
|
|
1445
|
+
` ⢠Epochs: ${result.epochsCompleted}\n` +
|
|
1446
|
+
` ⢠Final Loss: ${result.finalLoss.toFixed(4)}\n` +
|
|
1447
|
+
` ⢠Avg Reward: ${result.avgReward.toFixed(3)}\n` +
|
|
1448
|
+
` ⢠Convergence Rate: ${(result.convergenceRate * 100).toFixed(1)}%\n` +
|
|
1449
|
+
` ⢠Training Time: ${result.trainingTimeMs}ms\n\n` +
|
|
1450
|
+
`š¾ Trained policy saved to database\n` +
|
|
1451
|
+
`⨠Ready for improved predictions!`,
|
|
1452
|
+
},
|
|
1453
|
+
],
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
// ======================================================================
|
|
1458
|
+
// LEARNING SYSTEM TOOLS (v1.4.0 - Tools 6-10) - IMPLEMENTATIONS
|
|
1459
|
+
// ======================================================================
|
|
1460
|
+
case 'learning_metrics': {
|
|
1461
|
+
const sessionId = args?.session_id as string | undefined;
|
|
1462
|
+
const timeWindowDays = (args?.time_window_days as number) || 7;
|
|
1463
|
+
const includeTrends = (args?.include_trends as boolean) !== false;
|
|
1464
|
+
const groupBy = (args?.group_by as 'task' | 'session' | 'skill') || 'task';
|
|
1465
|
+
|
|
1466
|
+
const metrics = await learningSystem.getMetrics({
|
|
1467
|
+
sessionId,
|
|
1468
|
+
timeWindowDays,
|
|
1469
|
+
includeTrends,
|
|
1470
|
+
groupBy,
|
|
1471
|
+
});
|
|
1472
|
+
|
|
1473
|
+
return {
|
|
1474
|
+
content: [
|
|
1475
|
+
{
|
|
1476
|
+
type: 'text',
|
|
1477
|
+
text: `š Learning Performance Metrics\n\n` +
|
|
1478
|
+
`ā±ļø Time Window: ${timeWindowDays} days\n\n` +
|
|
1479
|
+
`š Overall Performance:\n` +
|
|
1480
|
+
` ⢠Total Episodes: ${metrics.overall.totalEpisodes}\n` +
|
|
1481
|
+
` ⢠Success Rate: ${(metrics.overall.successRate * 100).toFixed(1)}%\n` +
|
|
1482
|
+
` ⢠Avg Reward: ${metrics.overall.avgReward.toFixed(3)}\n` +
|
|
1483
|
+
` ⢠Reward Range: [${metrics.overall.minReward.toFixed(2)}, ${metrics.overall.maxReward.toFixed(2)}]\n` +
|
|
1484
|
+
` ⢠Avg Latency: ${metrics.overall.avgLatencyMs.toFixed(0)}ms\n\n` +
|
|
1485
|
+
`šÆ Top ${groupBy.charAt(0).toUpperCase() + groupBy.slice(1)}s:\n` +
|
|
1486
|
+
metrics.groupedMetrics.slice(0, 5).map((g, i) =>
|
|
1487
|
+
` ${i + 1}. ${g.key.substring(0, 40)}${g.key.length > 40 ? '...' : ''}\n` +
|
|
1488
|
+
` Count: ${g.count}, Success: ${(g.successRate * 100).toFixed(1)}%, Reward: ${g.avgReward.toFixed(2)}`
|
|
1489
|
+
).join('\n') +
|
|
1490
|
+
(metrics.groupedMetrics.length === 0 ? ' No data available' : '') +
|
|
1491
|
+
(includeTrends && metrics.trends.length > 0 ? `\n\nš Recent Trends (last ${Math.min(7, metrics.trends.length)} days):\n` +
|
|
1492
|
+
metrics.trends.slice(-7).map((t) =>
|
|
1493
|
+
` ${t.date}: ${t.count} episodes, ${(t.successRate * 100).toFixed(1)}% success`
|
|
1494
|
+
).join('\n') : '') +
|
|
1495
|
+
(metrics.policyImprovement.versions > 0 ? `\n\nš§ Policy Improvement:\n` +
|
|
1496
|
+
` ⢠Versions: ${metrics.policyImprovement.versions}\n` +
|
|
1497
|
+
` ⢠Q-Value Improvement: ${metrics.policyImprovement.qValueImprovement >= 0 ? '+' : ''}${metrics.policyImprovement.qValueImprovement.toFixed(3)}` : ''),
|
|
1498
|
+
},
|
|
1499
|
+
],
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
case 'learning_transfer': {
|
|
1504
|
+
const sourceSession = args?.source_session as string | undefined;
|
|
1505
|
+
const targetSession = args?.target_session as string | undefined;
|
|
1506
|
+
const sourceTask = args?.source_task as string | undefined;
|
|
1507
|
+
const targetTask = args?.target_task as string | undefined;
|
|
1508
|
+
const minSimilarity = (args?.min_similarity as number) || 0.7;
|
|
1509
|
+
const transferType = (args?.transfer_type as any) || 'all';
|
|
1510
|
+
const maxTransfers = (args?.max_transfers as number) || 10;
|
|
1511
|
+
|
|
1512
|
+
const result = await learningSystem.transferLearning({
|
|
1513
|
+
sourceSession,
|
|
1514
|
+
targetSession,
|
|
1515
|
+
sourceTask,
|
|
1516
|
+
targetTask,
|
|
1517
|
+
minSimilarity,
|
|
1518
|
+
transferType,
|
|
1519
|
+
maxTransfers,
|
|
1520
|
+
});
|
|
1521
|
+
|
|
1522
|
+
return {
|
|
1523
|
+
content: [
|
|
1524
|
+
{
|
|
1525
|
+
type: 'text',
|
|
1526
|
+
text: `š Learning Transfer Completed!\n\n` +
|
|
1527
|
+
`š¤ Source: ${sourceSession ? `Session ${sourceSession}` : `Task "${sourceTask}"`}\n` +
|
|
1528
|
+
`š„ Target: ${targetSession ? `Session ${targetSession}` : `Task "${targetTask}"`}\n` +
|
|
1529
|
+
`šÆ Transfer Type: ${transferType}\n` +
|
|
1530
|
+
`š Min Similarity: ${(minSimilarity * 100).toFixed(0)}%\n\n` +
|
|
1531
|
+
`ā
Transferred:\n` +
|
|
1532
|
+
` ⢠Episodes: ${result.transferred.episodes}\n` +
|
|
1533
|
+
` ⢠Skills/Q-Values: ${result.transferred.skills}\n` +
|
|
1534
|
+
` ⢠Causal Edges: ${result.transferred.causalEdges}\n` +
|
|
1535
|
+
(result.transferred.details.length > 0 ? `\nš Transfer Details:\n` +
|
|
1536
|
+
result.transferred.details.slice(0, 5).map((d: any, i: number) =>
|
|
1537
|
+
` ${i + 1}. ${d.type} #${d.id} (similarity: ${(d.similarity * 100).toFixed(1)}%)`
|
|
1538
|
+
).join('\n') : '') +
|
|
1539
|
+
`\n\nš” Knowledge successfully transferred for reuse!`,
|
|
1540
|
+
},
|
|
1541
|
+
],
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
case 'learning_explain': {
|
|
1546
|
+
const query = args?.query as string;
|
|
1547
|
+
const k = (args?.k as number) || 5;
|
|
1548
|
+
const explainDepth = (args?.explain_depth as any) || 'detailed';
|
|
1549
|
+
const includeConfidence = (args?.include_confidence as boolean) !== false;
|
|
1550
|
+
const includeEvidence = (args?.include_evidence as boolean) !== false;
|
|
1551
|
+
const includeCausal = (args?.include_causal as boolean) !== false;
|
|
1552
|
+
|
|
1553
|
+
const explanation = await learningSystem.explainAction({
|
|
1554
|
+
query,
|
|
1555
|
+
k,
|
|
1556
|
+
explainDepth,
|
|
1557
|
+
includeConfidence,
|
|
1558
|
+
includeEvidence,
|
|
1559
|
+
includeCausal,
|
|
1560
|
+
});
|
|
1561
|
+
|
|
1562
|
+
return {
|
|
1563
|
+
content: [
|
|
1564
|
+
{
|
|
1565
|
+
type: 'text',
|
|
1566
|
+
text: `š AI Action Recommendations (Explainable)\n\n` +
|
|
1567
|
+
`šÆ Query: ${query}\n\n` +
|
|
1568
|
+
`š” Recommended Actions:\n` +
|
|
1569
|
+
explanation.recommendations.map((rec: any, i: number) =>
|
|
1570
|
+
`${i + 1}. ${rec.action}\n` +
|
|
1571
|
+
` ⢠Confidence: ${(rec.confidence * 100).toFixed(1)}%\n` +
|
|
1572
|
+
` ⢠Success Rate: ${(rec.successRate * 100).toFixed(1)}%\n` +
|
|
1573
|
+
` ⢠Avg Reward: ${rec.avgReward.toFixed(3)}\n` +
|
|
1574
|
+
` ⢠Supporting Examples: ${rec.supportingExamples}\n` +
|
|
1575
|
+
(includeEvidence && rec.evidence ? ` ⢠Evidence:\n` +
|
|
1576
|
+
rec.evidence.map((e: any) =>
|
|
1577
|
+
` - Episode ${e.episodeId}: reward=${e.reward.toFixed(2)}, similarity=${(e.similarity * 100).toFixed(1)}%`
|
|
1578
|
+
).join('\n') : '')
|
|
1579
|
+
).join('\n\n') +
|
|
1580
|
+
(explainDepth !== 'summary' && explanation.reasoning ? `\n\nš§ Reasoning:\n` +
|
|
1581
|
+
` ⢠Similar Experiences Found: ${explanation.reasoning.similarExperiencesFound}\n` +
|
|
1582
|
+
` ⢠Avg Similarity: ${(explanation.reasoning.avgSimilarity * 100).toFixed(1)}%\n` +
|
|
1583
|
+
` ⢠Unique Actions Considered: ${explanation.reasoning.uniqueActions}` : '') +
|
|
1584
|
+
(includeCausal && explanation.causalChains && explanation.causalChains.length > 0 ? `\n\nš Causal Reasoning Chains:\n` +
|
|
1585
|
+
explanation.causalChains.slice(0, 3).map((chain: any, i: number) =>
|
|
1586
|
+
` ${i + 1}. ${chain.fromMemoryType} ā ${chain.toMemoryType} (uplift: ${(chain.uplift || 0).toFixed(3)})`
|
|
1587
|
+
).join('\n') : ''),
|
|
1588
|
+
},
|
|
1589
|
+
],
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
case 'experience_record': {
|
|
1594
|
+
const sessionId = args?.session_id as string;
|
|
1595
|
+
const toolName = args?.tool_name as string;
|
|
1596
|
+
const action = args?.action as string;
|
|
1597
|
+
const stateBefore = args?.state_before as any;
|
|
1598
|
+
const stateAfter = args?.state_after as any;
|
|
1599
|
+
const outcome = args?.outcome as string;
|
|
1600
|
+
const reward = args?.reward as number;
|
|
1601
|
+
const success = args?.success as boolean;
|
|
1602
|
+
const latencyMs = args?.latency_ms as number | undefined;
|
|
1603
|
+
const metadata = args?.metadata as any;
|
|
1604
|
+
|
|
1605
|
+
const experienceId = await learningSystem.recordExperience({
|
|
1606
|
+
sessionId,
|
|
1607
|
+
toolName,
|
|
1608
|
+
action,
|
|
1609
|
+
stateBefore,
|
|
1610
|
+
stateAfter,
|
|
1611
|
+
outcome,
|
|
1612
|
+
reward,
|
|
1613
|
+
success,
|
|
1614
|
+
latencyMs,
|
|
1615
|
+
metadata,
|
|
1616
|
+
});
|
|
1617
|
+
|
|
1618
|
+
return {
|
|
1619
|
+
content: [
|
|
1620
|
+
{
|
|
1621
|
+
type: 'text',
|
|
1622
|
+
text: `ā
Experience recorded successfully!\n\n` +
|
|
1623
|
+
`š Experience ID: ${experienceId}\n` +
|
|
1624
|
+
`š Session: ${sessionId}\n` +
|
|
1625
|
+
`š§ Tool: ${toolName}\n` +
|
|
1626
|
+
`š¬ Action: ${action}\n` +
|
|
1627
|
+
`š Outcome: ${outcome}\n` +
|
|
1628
|
+
`š Reward: ${reward.toFixed(3)}\n` +
|
|
1629
|
+
`${success ? 'ā
' : 'ā'} Success: ${success}\n` +
|
|
1630
|
+
(latencyMs ? `ā±ļø Latency: ${latencyMs}ms\n` : '') +
|
|
1631
|
+
`\nš¾ Experience stored for offline learning and future recommendations`,
|
|
1632
|
+
},
|
|
1633
|
+
],
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
case 'reward_signal': {
|
|
1638
|
+
const episodeId = args?.episode_id as number | undefined;
|
|
1639
|
+
const success = args?.success as boolean;
|
|
1640
|
+
const targetAchieved = (args?.target_achieved as boolean) !== false;
|
|
1641
|
+
const efficiencyScore = (args?.efficiency_score as number) || 0.5;
|
|
1642
|
+
const qualityScore = (args?.quality_score as number) || 0.5;
|
|
1643
|
+
const timeTakenMs = args?.time_taken_ms as number | undefined;
|
|
1644
|
+
const expectedTimeMs = args?.expected_time_ms as number | undefined;
|
|
1645
|
+
const includeCausal = (args?.include_causal as boolean) !== false;
|
|
1646
|
+
const rewardFunction = (args?.reward_function as any) || 'standard';
|
|
1647
|
+
|
|
1648
|
+
const reward = learningSystem.calculateReward({
|
|
1649
|
+
episodeId,
|
|
1650
|
+
success,
|
|
1651
|
+
targetAchieved,
|
|
1652
|
+
efficiencyScore,
|
|
1653
|
+
qualityScore,
|
|
1654
|
+
timeTakenMs,
|
|
1655
|
+
expectedTimeMs,
|
|
1656
|
+
includeCausal,
|
|
1657
|
+
rewardFunction,
|
|
1658
|
+
});
|
|
1659
|
+
|
|
1660
|
+
return {
|
|
1661
|
+
content: [
|
|
1662
|
+
{
|
|
1663
|
+
type: 'text',
|
|
1664
|
+
text: `šÆ Reward Signal Calculated\n\n` +
|
|
1665
|
+
`š Final Reward: ${reward.toFixed(3)}\n` +
|
|
1666
|
+
`š§ Reward Function: ${rewardFunction}\n\n` +
|
|
1667
|
+
`š Input Factors:\n` +
|
|
1668
|
+
` ⢠Success: ${success ? 'ā
' : 'ā'}\n` +
|
|
1669
|
+
` ⢠Target Achieved: ${targetAchieved ? 'ā
' : 'ā'}\n` +
|
|
1670
|
+
` ⢠Efficiency Score: ${(efficiencyScore * 100).toFixed(1)}%\n` +
|
|
1671
|
+
` ⢠Quality Score: ${(qualityScore * 100).toFixed(1)}%\n` +
|
|
1672
|
+
(timeTakenMs && expectedTimeMs ? ` ⢠Time Efficiency: ${((expectedTimeMs / timeTakenMs) * 100).toFixed(1)}%\n` : '') +
|
|
1673
|
+
(includeCausal ? ` ⢠Causal Impact: Included\n` : '') +
|
|
1674
|
+
`\nš” Use this reward signal for learning feedback`,
|
|
1675
|
+
},
|
|
1676
|
+
],
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
default:
|
|
1681
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
1682
|
+
}
|
|
1683
|
+
} catch (error: any) {
|
|
1684
|
+
return {
|
|
1685
|
+
content: [
|
|
1686
|
+
{
|
|
1687
|
+
type: 'text',
|
|
1688
|
+
text: `ā Error: ${error.message}\n${error.stack || ''}`,
|
|
1689
|
+
},
|
|
1690
|
+
],
|
|
1691
|
+
isError: true,
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
});
|
|
1695
|
+
|
|
1696
|
+
// ============================================================================
|
|
1697
|
+
// Start Server
|
|
1698
|
+
// ============================================================================
|
|
1699
|
+
async function main() {
|
|
1700
|
+
const transport = new StdioServerTransport();
|
|
1701
|
+
await server.connect(transport);
|
|
1702
|
+
console.error('š AgentDB MCP Server v1.3.0 running on stdio');
|
|
1703
|
+
console.error('š¦ 29 tools available (5 core vector DB + 9 frontier + 10 learning + 5 AgentDB tools)');
|
|
1704
|
+
console.error('š§ Embedding service initialized');
|
|
1705
|
+
console.error('š Learning system ready (9 RL algorithms)');
|
|
1706
|
+
console.error('⨠New learning tools: metrics, transfer, explain, experience_record, reward_signal');
|
|
1707
|
+
console.error('š¬ Extended features: transfer learning, XAI explanations, reward shaping');
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
main().catch(console.error);
|