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