@gotza02/seq-thinking 1.1.5 → 1.1.6
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 +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp-server.js +1 -1
- package/package.json +8 -2
- package/agents_test.log +0 -15
- package/data/agents/1770106504306-dljh9ef.json +0 -68
- package/data/agents/1770106504310-4oarrst.json +0 -58
- package/data/agents/1770106540588-pvitt55.json +0 -68
- package/data/agents/1770106540595-z2ya871.json +0 -58
- package/data/agents/1770106710890-0e2naq1.json +0 -68
- package/data/agents/1770106710893-r076yxx.json +0 -58
- package/data/agents/1770109212161-4ybd0i7.json +0 -68
- package/data/agents/1770109212166-gkhya8h.json +0 -58
- package/data/agents/1770117726716-lrnm415.json +0 -68
- package/data/agents/1770117726719-w6hsf3v.json +0 -58
- package/data/sessions/1770100622009-5afiuyv.json +0 -499
- package/data/sessions/1770106504312-75zk750.json +0 -107
- package/data/sessions/1770106540597-z8e8soo.json +0 -150
- package/data/sessions/1770106710894-0kxgy5x.json +0 -150
- package/data/sessions/1770109212169-zpddeb9.json +0 -150
- package/data/sessions/1770117726720-frcwj99.json +0 -150
- package/real_world_test.log +0 -200
- package/real_world_test_dynamic.log +0 -184
- package/real_world_test_real.log +0 -184
- package/src/__tests__/agents.test.ts +0 -858
- package/src/__tests__/mcp-server.test.ts +0 -380
- package/src/__tests__/sequential-thinking.test.ts +0 -687
- package/src/__tests__/swarm-coordinator.test.ts +0 -903
- package/src/__tests__/types.test.ts +0 -839
- package/src/__tests__/utils.test.ts +0 -322
- package/src/agents/base-agent.ts +0 -288
- package/src/agents/critic-agent.ts +0 -582
- package/src/agents/index.ts +0 -11
- package/src/agents/meta-reasoning-agent.ts +0 -314
- package/src/agents/reasoner-agent.ts +0 -312
- package/src/agents/synthesizer-agent.ts +0 -641
- package/src/index.ts +0 -118
- package/src/mcp-server.ts +0 -391
- package/src/real_world_test.ts +0 -89
- package/src/sequential-thinking.ts +0 -614
- package/src/swarm-coordinator.ts +0 -772
- package/src/types/index.ts +0 -915
- package/src/utils/index.ts +0 -1004
- package/src/utils/llm-adapter.ts +0 -110
- package/src/utils/logger.ts +0 -56
- package/src/utils/persistence.ts +0 -109
- package/test_output.log +0 -0
- package/tsconfig.json +0 -21
package/src/index.ts
DELETED
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MCP Sequential Thinking with Swarm Agents
|
|
3
|
-
* Main entry point for the library
|
|
4
|
-
* @module mcp-sequential-thinking
|
|
5
|
-
* @version 1.0.0
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
// Export MCP Server
|
|
9
|
-
export { MCPServer } from './mcp-server.js';
|
|
10
|
-
|
|
11
|
-
// Export Sequential Thinking components
|
|
12
|
-
export {
|
|
13
|
-
SessionManager,
|
|
14
|
-
ThoughtGraph,
|
|
15
|
-
MetaReasoningEngine,
|
|
16
|
-
SelfCorrectionEngine,
|
|
17
|
-
AdaptiveGranularityEngine,
|
|
18
|
-
ConfidenceCalibrator
|
|
19
|
-
} from './sequential-thinking.js';
|
|
20
|
-
|
|
21
|
-
// Export Swarm Coordinator components
|
|
22
|
-
export {
|
|
23
|
-
SwarmCoordinator,
|
|
24
|
-
AgentRegistry,
|
|
25
|
-
MessageBroker,
|
|
26
|
-
TaskQueueManager,
|
|
27
|
-
TaskAssigner,
|
|
28
|
-
ConsensusEngine,
|
|
29
|
-
ConflictResolver
|
|
30
|
-
} from './swarm-coordinator.js';
|
|
31
|
-
|
|
32
|
-
// Export Agents
|
|
33
|
-
export {
|
|
34
|
-
BaseAgent,
|
|
35
|
-
ReasonerAgent,
|
|
36
|
-
CriticAgent,
|
|
37
|
-
SynthesizerAgent,
|
|
38
|
-
MetaReasoningAgent
|
|
39
|
-
} from './agents/index.js';
|
|
40
|
-
|
|
41
|
-
// Export all types
|
|
42
|
-
export * from './types/index.js';
|
|
43
|
-
|
|
44
|
-
// Export utilities (avoiding Result conflict)
|
|
45
|
-
export {
|
|
46
|
-
generateId,
|
|
47
|
-
generateUUID,
|
|
48
|
-
generateShortId,
|
|
49
|
-
clamp,
|
|
50
|
-
clampConfidence,
|
|
51
|
-
lerp,
|
|
52
|
-
roundTo,
|
|
53
|
-
extractWords,
|
|
54
|
-
calculateJaccardSimilarity,
|
|
55
|
-
calculateSimilarity,
|
|
56
|
-
calculateCosineSimilarity,
|
|
57
|
-
extractNGrams,
|
|
58
|
-
calculateNGramSimilarity,
|
|
59
|
-
calculateMean,
|
|
60
|
-
calculateWeightedAverage,
|
|
61
|
-
calculateMedian,
|
|
62
|
-
calculateStandardDeviation,
|
|
63
|
-
calculateVariance,
|
|
64
|
-
findMin,
|
|
65
|
-
findMax,
|
|
66
|
-
normalizeValues,
|
|
67
|
-
calculatePercentile,
|
|
68
|
-
formatDuration,
|
|
69
|
-
formatTimestamp,
|
|
70
|
-
formatRelativeTime,
|
|
71
|
-
deepClone,
|
|
72
|
-
deepCloneWithDates,
|
|
73
|
-
deepMerge,
|
|
74
|
-
deepEqual,
|
|
75
|
-
pick,
|
|
76
|
-
omit,
|
|
77
|
-
validateUUID,
|
|
78
|
-
isNonEmptyString,
|
|
79
|
-
isPositiveNumber,
|
|
80
|
-
isInRange,
|
|
81
|
-
isNonEmptyArray,
|
|
82
|
-
isPlainObject,
|
|
83
|
-
sanitizeString,
|
|
84
|
-
truncateString,
|
|
85
|
-
toCamelCase,
|
|
86
|
-
toPascalCase,
|
|
87
|
-
toSnakeCase,
|
|
88
|
-
toKebabCase,
|
|
89
|
-
escapeRegExp,
|
|
90
|
-
unique,
|
|
91
|
-
uniqueBy,
|
|
92
|
-
groupBy,
|
|
93
|
-
partition,
|
|
94
|
-
shuffle,
|
|
95
|
-
sample,
|
|
96
|
-
chunk,
|
|
97
|
-
flatten,
|
|
98
|
-
deepFlatten,
|
|
99
|
-
sleep,
|
|
100
|
-
createTimeoutPromise,
|
|
101
|
-
withTimeout,
|
|
102
|
-
retry,
|
|
103
|
-
debounce,
|
|
104
|
-
throttle,
|
|
105
|
-
tryCatch,
|
|
106
|
-
tryCatchAsync,
|
|
107
|
-
createError
|
|
108
|
-
} from './utils/index.js';
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Library version
|
|
112
|
-
*/
|
|
113
|
-
export const VERSION = '1.1.5';
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Default export - MCPServer
|
|
117
|
-
*/
|
|
118
|
-
export { MCPServer as default } from './mcp-server.js';
|
package/src/mcp-server.ts
DELETED
|
@@ -1,391 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* MCP Server
|
|
4
|
-
*/
|
|
5
|
-
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
6
|
-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
|
-
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
8
|
-
import { SessionManager, SelfCorrectionEngine, AdaptiveGranularityEngine } from './sequential-thinking.js';
|
|
9
|
-
import { SwarmCoordinator } from './swarm-coordinator.js';
|
|
10
|
-
import { ThoughtType, AgentType, ReasoningStrategy, CriticType, SynthesizerType, ConsensusAlgorithm, ConflictResolutionStrategy } from './types/index.js';
|
|
11
|
-
import { ReasonerAgent, CriticAgent, SynthesizerAgent, MetaReasoningAgent } from './agents/index.js';
|
|
12
|
-
import { Logger } from './utils/logger.js';
|
|
13
|
-
const SEQUENTIAL_THINKING_TOOL = {
|
|
14
|
-
name: 'advanced_sequential_thinking',
|
|
15
|
-
description: 'Advanced sequential thinking with self-correction, parallel hypotheses, meta-reasoning',
|
|
16
|
-
inputSchema: {
|
|
17
|
-
type: 'object',
|
|
18
|
-
properties: {
|
|
19
|
-
operation: {
|
|
20
|
-
type: 'string',
|
|
21
|
-
enum: [
|
|
22
|
-
'initialize', 'add_thought', 'revise_thought', 'branch_thought',
|
|
23
|
-
'merge_branches', 'prune_branch', 'self_correct', 'add_meta_thought',
|
|
24
|
-
'get_thinking_path', 'get_branch_comparison', 'calibrate_confidence',
|
|
25
|
-
'adjust_granularity', 'get_session_state', 'complete_session',
|
|
26
|
-
'delegate_to_swarm'
|
|
27
|
-
]
|
|
28
|
-
},
|
|
29
|
-
sessionId: { type: 'string' },
|
|
30
|
-
topic: { type: 'string' },
|
|
31
|
-
content: { type: 'string' },
|
|
32
|
-
thoughtType: { type: 'string', enum: Object.values(ThoughtType) },
|
|
33
|
-
thoughtId: { type: 'string' },
|
|
34
|
-
parentThoughtId: { type: 'string' },
|
|
35
|
-
branchId: { type: 'string' },
|
|
36
|
-
confidence: { type: 'number' },
|
|
37
|
-
revisionReason: { type: 'string' },
|
|
38
|
-
branchName: { type: 'string' },
|
|
39
|
-
branchDescription: { type: 'string' },
|
|
40
|
-
tags: { type: 'array', items: { type: 'string' } },
|
|
41
|
-
assumptions: { type: 'array', items: { type: 'string' } },
|
|
42
|
-
dependencies: { type: 'array', items: { type: 'string' } },
|
|
43
|
-
settings: { type: 'object' },
|
|
44
|
-
modelProvider: { type: 'string', description: 'Optional LLM provider (gemini, claude, kimi)' }
|
|
45
|
-
},
|
|
46
|
-
required: ['operation']
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
const SWARM_COORDINATION_TOOL = {
|
|
50
|
-
name: 'swarm_agent_coordination',
|
|
51
|
-
description: 'Coordinate multiple AI agents in a swarm',
|
|
52
|
-
inputSchema: {
|
|
53
|
-
type: 'object',
|
|
54
|
-
properties: {
|
|
55
|
-
operation: {
|
|
56
|
-
type: 'string',
|
|
57
|
-
enum: [
|
|
58
|
-
'register_agent', 'unregister_agent', 'list_agents', 'get_agent_status',
|
|
59
|
-
'assign_task', 'get_task_status', 'reach_consensus', 'identify_conflict',
|
|
60
|
-
'resolve_conflict', 'broadcast_message', 'send_direct_message', 'get_swarm_stats'
|
|
61
|
-
]
|
|
62
|
-
},
|
|
63
|
-
name: { type: 'string' },
|
|
64
|
-
agentType: { type: 'string', enum: Object.values(AgentType) },
|
|
65
|
-
subtype: { type: 'string' },
|
|
66
|
-
capabilities: { type: 'array' },
|
|
67
|
-
agentId: { type: 'string' },
|
|
68
|
-
taskType: { type: 'string' },
|
|
69
|
-
description: { type: 'string' },
|
|
70
|
-
input: {},
|
|
71
|
-
requiredCapabilities: { type: 'array', items: { type: 'string' } },
|
|
72
|
-
strategy: { type: 'string', enum: ['round_robin', 'capability_based', 'load_balanced', 'adaptive'] },
|
|
73
|
-
proposal: {},
|
|
74
|
-
options: { type: 'array' },
|
|
75
|
-
algorithm: { type: 'string', enum: Object.values(ConsensusAlgorithm) },
|
|
76
|
-
participatingAgents: { type: 'array', items: { type: 'string' } },
|
|
77
|
-
minAgreementRatio: { type: 'number' },
|
|
78
|
-
maxRounds: { type: 'number' },
|
|
79
|
-
conflictType: { type: 'string' },
|
|
80
|
-
positions: { type: 'array' },
|
|
81
|
-
conflictId: { type: 'string' },
|
|
82
|
-
resolutionStrategy: { type: 'string', enum: Object.values(ConflictResolutionStrategy) },
|
|
83
|
-
resolverAgentId: { type: 'string' },
|
|
84
|
-
senderId: { type: 'string' },
|
|
85
|
-
recipientId: { type: 'string' },
|
|
86
|
-
payload: {},
|
|
87
|
-
taskId: { type: 'string' }
|
|
88
|
-
},
|
|
89
|
-
required: ['operation']
|
|
90
|
-
}
|
|
91
|
-
};
|
|
92
|
-
export class MCPServer {
|
|
93
|
-
server;
|
|
94
|
-
sessionManager;
|
|
95
|
-
swarmCoordinator;
|
|
96
|
-
registeredAgents = new Map();
|
|
97
|
-
private dataDir = './data';
|
|
98
|
-
|
|
99
|
-
constructor() {
|
|
100
|
-
this.server = new Server({ name: 'mcp-sequential-thinking', version: '1.1.5' }, { capabilities: { tools: {} } });
|
|
101
|
-
this.sessionManager = new SessionManager(this.dataDir);
|
|
102
|
-
this.swarmCoordinator = new SwarmCoordinator(this.dataDir);
|
|
103
|
-
this.setupHandlers();
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
async initialize() {
|
|
107
|
-
await this.sessionManager.initialize();
|
|
108
|
-
await this.swarmCoordinator.initialize();
|
|
109
|
-
}
|
|
110
|
-
setupHandlers() {
|
|
111
|
-
this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
112
|
-
tools: [SEQUENTIAL_THINKING_TOOL, SWARM_COORDINATION_TOOL]
|
|
113
|
-
}));
|
|
114
|
-
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
115
|
-
const { name, arguments: args } = request.params;
|
|
116
|
-
try {
|
|
117
|
-
if (name === 'advanced_sequential_thinking') {
|
|
118
|
-
const result = await this.handleSequentialThinking(args);
|
|
119
|
-
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
120
|
-
}
|
|
121
|
-
if (name === 'swarm_agent_coordination') {
|
|
122
|
-
const result = await this.handleSwarmCoordination(args);
|
|
123
|
-
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
124
|
-
}
|
|
125
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
return {
|
|
129
|
-
content: [{ type: 'text', text: JSON.stringify({ success: false, error: error instanceof Error ? error.message : String(error) }, null, 2) }],
|
|
130
|
-
isError: true
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
async handleSequentialThinking(args: any) {
|
|
136
|
-
const operation = String(args.operation);
|
|
137
|
-
switch (operation) {
|
|
138
|
-
case 'initialize': {
|
|
139
|
-
const session = await this.sessionManager.createSession(String(args.topic), args.settings || {});
|
|
140
|
-
return { success: true, sessionId: session.id, topic: session.topic, status: session.status, settings: session.settings };
|
|
141
|
-
}
|
|
142
|
-
case 'add_thought': {
|
|
143
|
-
const { thought, metaNote, issues } = await this.sessionManager.addThought(String(args.sessionId), String(args.content), {
|
|
144
|
-
thoughtType: args.thoughtType,
|
|
145
|
-
parentThoughtId: args.parentThoughtId,
|
|
146
|
-
branchId: args.branchId,
|
|
147
|
-
confidence: args.confidence,
|
|
148
|
-
tags: args.tags,
|
|
149
|
-
assumptions: args.assumptions,
|
|
150
|
-
dependencies: args.dependencies
|
|
151
|
-
});
|
|
152
|
-
return {
|
|
153
|
-
success: true,
|
|
154
|
-
thought: { id: thought.id, stepNumber: thought.stepNumber, thoughtType: thought.thoughtType, confidence: thought.confidence, branchId: thought.branchId },
|
|
155
|
-
metaNote: metaNote ? { id: metaNote.id, type: metaNote.observationType, content: metaNote.content, triggeredActions: metaNote.triggeredActions } : undefined,
|
|
156
|
-
issuesDetected: issues
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
case 'revise_thought': {
|
|
160
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
161
|
-
const revision = graph.reviseThought(String(args.thoughtId), String(args.newContent), String(args.revisionReason));
|
|
162
|
-
return { success: true, revision: { id: revision.id, originalThoughtId: args.thoughtId, content: revision.content, revisionReason: args.revisionReason } };
|
|
163
|
-
}
|
|
164
|
-
case 'branch_thought': {
|
|
165
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
166
|
-
const { branch, thought } = graph.createBranch(String(args.sessionId), String(args.parentThoughtId), String(args.branchName), String(args.branchDescription), String(args.initialContent));
|
|
167
|
-
return { success: true, branch: { id: branch.id, name: branch.name, description: branch.description, parentBranchId: branch.parentBranchId }, rootThought: { id: thought.id, content: thought.content } };
|
|
168
|
-
}
|
|
169
|
-
case 'merge_branches': {
|
|
170
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
171
|
-
const mergeThought = graph.mergeBranches(String(args.targetBranchId), String(args.sourceBranchId), String(args.mergeContent));
|
|
172
|
-
return { success: true, mergeThought: { id: mergeThought.id, content: mergeThought.content, mergedBranches: [args.sourceBranchId] } };
|
|
173
|
-
}
|
|
174
|
-
case 'prune_branch': {
|
|
175
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
176
|
-
graph.pruneBranch(String(args.branchId), String(args.reason));
|
|
177
|
-
return { success: true, message: `Branch ${args.branchId} pruned: ${args.reason}` };
|
|
178
|
-
}
|
|
179
|
-
case 'self_correct': {
|
|
180
|
-
const session = this.sessionManager.getSession(String(args.sessionId));
|
|
181
|
-
if (!session)
|
|
182
|
-
throw new Error(`Session not found: ${args.sessionId}`);
|
|
183
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
184
|
-
const thought = graph.getThoughts().get(String(args.thoughtId));
|
|
185
|
-
if (!thought)
|
|
186
|
-
throw new Error(`Thought not found: ${args.thoughtId}`);
|
|
187
|
-
const correctionEngine = new SelfCorrectionEngine();
|
|
188
|
-
const issues = await correctionEngine.detectIssues(thought, graph);
|
|
189
|
-
return { success: true, issuesDetected: issues, recommendations: issues.map((i: any) => i.suggestion) };
|
|
190
|
-
}
|
|
191
|
-
case 'add_meta_thought': {
|
|
192
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
193
|
-
const metaEngine = this.sessionManager.getMetaEngine();
|
|
194
|
-
const metaNote = metaEngine.generateMetaObservation(String(args.thoughtId), graph);
|
|
195
|
-
return { success: true, metaNote: metaNote ? { id: metaNote.id, type: metaNote.observationType, content: metaNote.content, triggeredActions: metaNote.triggeredActions } : null };
|
|
196
|
-
}
|
|
197
|
-
case 'get_thinking_path': {
|
|
198
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
199
|
-
const path = graph.getThinkingPath(String(args.thoughtId));
|
|
200
|
-
return { success: true, path: path.map((t: any) => ({ id: t.id, stepNumber: t.stepNumber, thoughtType: t.thoughtType, content: t.content.substring(0, 200), confidence: t.confidence.overall })) };
|
|
201
|
-
}
|
|
202
|
-
case 'get_branch_comparison': {
|
|
203
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
204
|
-
const branchIds = Array.isArray(args.branchIds) ? args.branchIds : [];
|
|
205
|
-
const comparison = graph.getBranchComparison(branchIds);
|
|
206
|
-
return { success: true, comparison };
|
|
207
|
-
}
|
|
208
|
-
case 'calibrate_confidence': {
|
|
209
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
210
|
-
const thought = graph.getThoughts().get(String(args.thoughtId));
|
|
211
|
-
if (!thought)
|
|
212
|
-
throw new Error(`Thought not found: ${args.thoughtId}`);
|
|
213
|
-
return { success: true, originalConfidence: thought.confidence, message: 'Confidence calibration would update based on feedback' };
|
|
214
|
-
}
|
|
215
|
-
case 'adjust_granularity': {
|
|
216
|
-
const session = this.sessionManager.getSession(String(args.sessionId));
|
|
217
|
-
if (!session)
|
|
218
|
-
throw new Error(`Session not found: ${args.sessionId}`);
|
|
219
|
-
const engine = new AdaptiveGranularityEngine();
|
|
220
|
-
const granularity = await engine.calculateGranularity(session.topic, session.context, session.thoughts.size);
|
|
221
|
-
return { success: true, recommendedDetail: granularity.detail, reasoning: granularity.reasoning };
|
|
222
|
-
}
|
|
223
|
-
case 'get_session_state': {
|
|
224
|
-
const session = this.sessionManager.getSession(String(args.sessionId));
|
|
225
|
-
if (!session)
|
|
226
|
-
throw new Error(`Session not found: ${args.sessionId}`);
|
|
227
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
228
|
-
return {
|
|
229
|
-
success: true,
|
|
230
|
-
session: { id: session.id, topic: session.topic, status: session.status, totalThoughts: session.metadata.totalThoughts, totalBranches: session.metadata.totalBranches, lastActivity: session.metadata.lastActivityAt },
|
|
231
|
-
branches: Array.from(graph.getBranches().values()).map(b => ({ id: b.id, name: b.name, status: b.status, thoughtCount: b.thoughtIds.length, confidence: b.confidence })),
|
|
232
|
-
recentThoughts: Array.from(session.thoughts.values()).slice(-5).map((t: any) => ({ id: t.id, stepNumber: t.stepNumber, thoughtType: t.thoughtType, content: t.content.substring(0, 100) }))
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
case 'complete_session': {
|
|
236
|
-
await this.sessionManager.completeSession(String(args.sessionId));
|
|
237
|
-
return { success: true, message: `Session ${args.sessionId} completed` };
|
|
238
|
-
}
|
|
239
|
-
case 'delegate_to_swarm': {
|
|
240
|
-
const session = this.sessionManager.getSession(String(args.sessionId));
|
|
241
|
-
if (!session) throw new Error(`Session not found: ${args.sessionId}`);
|
|
242
|
-
|
|
243
|
-
const graph = this.sessionManager.getThoughtGraph();
|
|
244
|
-
const thought = graph.getThoughts().get(String(args.thoughtId));
|
|
245
|
-
if (!thought) throw new Error(`Thought not found: ${args.thoughtId}`);
|
|
246
|
-
|
|
247
|
-
const taskType = String(args.taskType || 'reasoning');
|
|
248
|
-
const { task, assignedAgent } = this.swarmCoordinator.submitTask(
|
|
249
|
-
taskType,
|
|
250
|
-
`Analyze and expand on this thought: ${thought.content}`,
|
|
251
|
-
{ thought: thought.content, context: session.context, modelProvider: args.modelProvider },
|
|
252
|
-
{ requiredCapabilities: args.requiredCapabilities || [], minConfidence: 0.6, maxTimeMs: 30000 }
|
|
253
|
-
);
|
|
254
|
-
|
|
255
|
-
if (!assignedAgent) {
|
|
256
|
-
return { success: false, error: 'No suitable agent available in swarm' };
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
const result = await this.swarmCoordinator.executeTask(task.id);
|
|
260
|
-
|
|
261
|
-
if (result.success && result.output) {
|
|
262
|
-
const swarmOutput = typeof result.output === 'string' ? result.output : JSON.stringify(result.output, null, 2);
|
|
263
|
-
const newThought = await this.sessionManager.addThought(session.id, swarmOutput, {
|
|
264
|
-
thoughtType: ThoughtType.SYNTHESIS,
|
|
265
|
-
parentThoughtId: thought.id,
|
|
266
|
-
branchId: thought.branchId,
|
|
267
|
-
confidence: result.confidence,
|
|
268
|
-
tags: ['swarm-result', assignedAgent.config.name]
|
|
269
|
-
});
|
|
270
|
-
return { success: true, swarmResult: result, newThought: newThought.thought };
|
|
271
|
-
} else {
|
|
272
|
-
return { success: false, error: 'Swarm execution failed', details: result };
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
default:
|
|
276
|
-
throw new Error(`Unknown operation: ${operation}`);
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
async handleSwarmCoordination(args: any) {
|
|
280
|
-
const operation = String(args.operation);
|
|
281
|
-
switch (operation) {
|
|
282
|
-
case 'register_agent': {
|
|
283
|
-
const agentType = String(args.agentType);
|
|
284
|
-
let agent;
|
|
285
|
-
switch (agentType) {
|
|
286
|
-
case AgentType.REASONER:
|
|
287
|
-
agent = new ReasonerAgent({ name: String(args.name), strategy: args.subtype || ReasoningStrategy.CHAIN_OF_THOUGHT });
|
|
288
|
-
break;
|
|
289
|
-
case AgentType.CRITIC:
|
|
290
|
-
agent = new CriticAgent({ name: String(args.name), criticType: args.subtype || CriticType.LOGICAL });
|
|
291
|
-
break;
|
|
292
|
-
case AgentType.SYNTHESIZER:
|
|
293
|
-
agent = new SynthesizerAgent({ name: String(args.name), synthesizerType: args.subtype || SynthesizerType.CONSENSUS });
|
|
294
|
-
break;
|
|
295
|
-
case AgentType.META_REASONING:
|
|
296
|
-
agent = new MetaReasoningAgent({ name: String(args.name) });
|
|
297
|
-
break;
|
|
298
|
-
default:
|
|
299
|
-
throw new Error(`Unsupported agent type: ${agentType}`);
|
|
300
|
-
}
|
|
301
|
-
this.registeredAgents.set(agent.id, agent);
|
|
302
|
-
await this.swarmCoordinator.registerAgent(agent);
|
|
303
|
-
return { success: true, agentId: agent.id, name: agent.config.name, type: agent.config.type, capabilities: agent.config.capabilities.map(c => c.name) };
|
|
304
|
-
}
|
|
305
|
-
case 'unregister_agent': {
|
|
306
|
-
const success = await this.swarmCoordinator.unregisterAgent(String(args.agentId));
|
|
307
|
-
this.registeredAgents.delete(String(args.agentId));
|
|
308
|
-
return { success, message: success ? `Agent ${args.agentId} unregistered` : 'Agent not found' };
|
|
309
|
-
}
|
|
310
|
-
case 'list_agents': {
|
|
311
|
-
const agents = this.swarmCoordinator.registry.getAllAgents();
|
|
312
|
-
return { success: true, agents: agents.map(a => ({ id: a.config.id, name: a.config.name, type: a.config.type, subtype: a.config.subtype, status: a.status, capabilities: a.config.capabilities.map(c => c.name) })) };
|
|
313
|
-
}
|
|
314
|
-
case 'get_agent_status': {
|
|
315
|
-
const agent = this.swarmCoordinator.registry.getAgent(String(args.agentId));
|
|
316
|
-
if (!agent)
|
|
317
|
-
throw new Error(`Agent not found: ${args.agentId}`);
|
|
318
|
-
return { success: true, agent: { id: agent.config.id, name: agent.config.name, type: agent.config.type, status: agent.status, currentTasks: agent.currentTasks, performanceMetrics: { tasksCompleted: agent.performanceHistory.length, averageQuality: agent.performanceHistory.length > 0 ? agent.performanceHistory.reduce((sum, p) => sum + p.quality, 0) / agent.performanceHistory.length : 0, averageTimeMs: agent.performanceHistory.length > 0 ? agent.performanceHistory.reduce((sum, p) => sum + p.timeMs, 0) / agent.performanceHistory.length : 0 } } };
|
|
319
|
-
}
|
|
320
|
-
case 'assign_task': {
|
|
321
|
-
const { task, assignedAgent } = this.swarmCoordinator.submitTask(String(args.taskType), String(args.description), args.input, { requiredCapabilities: Array.isArray(args.requiredCapabilities) ? args.requiredCapabilities : [], minConfidence: 0.6, maxTimeMs: 30000 }, args.strategy || 'adaptive');
|
|
322
|
-
|
|
323
|
-
let result = null;
|
|
324
|
-
if (assignedAgent) {
|
|
325
|
-
result = await this.swarmCoordinator.executeTask(task.id);
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
return {
|
|
329
|
-
success: true,
|
|
330
|
-
task: {
|
|
331
|
-
id: task.id,
|
|
332
|
-
type: task.type,
|
|
333
|
-
description: task.description,
|
|
334
|
-
status: task.status,
|
|
335
|
-
assignedAgentId: task.assignedAgentId
|
|
336
|
-
},
|
|
337
|
-
assignedAgent: assignedAgent ? {
|
|
338
|
-
id: assignedAgent.config.id,
|
|
339
|
-
name: assignedAgent.config.name,
|
|
340
|
-
type: assignedAgent.config.type
|
|
341
|
-
} : null,
|
|
342
|
-
result
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
case 'get_task_status': {
|
|
346
|
-
const task = this.swarmCoordinator.taskQueue.getTask(String(args.taskId));
|
|
347
|
-
if (!task)
|
|
348
|
-
throw new Error(`Task not found: ${args.taskId}`);
|
|
349
|
-
return { success: true, task: { id: task.id, type: task.type, description: task.description, status: task.status, assignedAgentId: task.assignedAgentId, result: task.result, createdAt: task.metadata.createdAt, completedAt: task.metadata.completedAt } };
|
|
350
|
-
}
|
|
351
|
-
case 'reach_consensus': {
|
|
352
|
-
const result = await this.swarmCoordinator.reachConsensus(args.proposal, Array.isArray(args.options) ? args.options : [], args.algorithm || ConsensusAlgorithm.WEIGHTED_VOTE, Array.isArray(args.participatingAgents) ? args.participatingAgents : undefined, typeof args.minAgreementRatio === 'number' ? args.minAgreementRatio : 0.67, typeof args.maxRounds === 'number' ? args.maxRounds : 3);
|
|
353
|
-
return { success: true, consensus: { proposalId: result.proposalId, algorithm: result.algorithm, winningOption: result.winningOption, confidence: result.confidence, agreementRatio: result.agreementRatio, rounds: result.metadata.rounds, dissentingOpinions: result.dissentingOpinions } };
|
|
354
|
-
}
|
|
355
|
-
case 'identify_conflict': {
|
|
356
|
-
const conflict = this.swarmCoordinator.identifyConflict(String(args.conflictType), String(args.description), Array.isArray(args.positions) ? args.positions : []);
|
|
357
|
-
return { success: true, conflict: { id: conflict.id, type: conflict.type, description: conflict.description, involvedAgents: conflict.involvedAgents, positions: conflict.conflictingPositions, status: conflict.status } };
|
|
358
|
-
}
|
|
359
|
-
case 'resolve_conflict': {
|
|
360
|
-
const { conflict, resolution } = this.swarmCoordinator.resolveConflict(String(args.conflictId), args.resolutionStrategy || ConflictResolutionStrategy.VOTING, args.resolverAgentId);
|
|
361
|
-
return { success: true, conflict: { id: conflict.id, status: conflict.status, resolutionStrategy: conflict.metadata.resolutionStrategy }, resolution };
|
|
362
|
-
}
|
|
363
|
-
case 'broadcast_message': {
|
|
364
|
-
const message = this.swarmCoordinator.broadcastMessage(String(args.senderId), args.payload);
|
|
365
|
-
return { success: true, message: { id: message.id, type: message.type, senderId: message.senderId, timestamp: message.timestamp } };
|
|
366
|
-
}
|
|
367
|
-
case 'send_direct_message': {
|
|
368
|
-
const message = this.swarmCoordinator.sendDirectMessage(String(args.senderId), String(args.recipientId), args.payload);
|
|
369
|
-
return { success: true, message: { id: message.id, type: message.type, senderId: message.senderId, recipientId: message.recipientId, timestamp: message.timestamp } };
|
|
370
|
-
}
|
|
371
|
-
case 'get_swarm_stats': {
|
|
372
|
-
const stats = this.swarmCoordinator.getSwarmStats();
|
|
373
|
-
return { success: true, stats };
|
|
374
|
-
}
|
|
375
|
-
default:
|
|
376
|
-
throw new Error(`Unknown operation: ${operation}`);
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
async start() {
|
|
380
|
-
await this.initialize();
|
|
381
|
-
const transport = new StdioServerTransport();
|
|
382
|
-
await this.server.connect(transport);
|
|
383
|
-
Logger.error('MCP Sequential Thinking Server running on stdio');
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
const isMainModule = import.meta.url === `file://${process.argv[1]}`;
|
|
387
|
-
if (isMainModule) {
|
|
388
|
-
const server = new MCPServer();
|
|
389
|
-
server.start().catch((error) => Logger.error('Server error', { error }));
|
|
390
|
-
}
|
|
391
|
-
//# sourceMappingURL=mcp-server.js.map
|
package/src/real_world_test.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { MCPServer } from './mcp-server.js';
|
|
2
|
-
import { Logger, LogLevel } from './utils/logger.js';
|
|
3
|
-
|
|
4
|
-
async function runTest() {
|
|
5
|
-
Logger.setLevel(LogLevel.INFO);
|
|
6
|
-
console.log('--- Starting Real World Scenario Test ---');
|
|
7
|
-
|
|
8
|
-
const server = new MCPServer();
|
|
9
|
-
await server.initialize();
|
|
10
|
-
console.log('[System] Server Initialized');
|
|
11
|
-
|
|
12
|
-
// 1. Register Agents
|
|
13
|
-
console.log('\n[Step 1] Registering Agents...');
|
|
14
|
-
const reasoner = await server.handleSwarmCoordination({
|
|
15
|
-
operation: 'register_agent',
|
|
16
|
-
name: 'LogicMaster',
|
|
17
|
-
agentType: 'reasoner',
|
|
18
|
-
subtype: 'chain_of_thought'
|
|
19
|
-
});
|
|
20
|
-
console.log('Registered Reasoner:', JSON.stringify(reasoner, null, 2));
|
|
21
|
-
|
|
22
|
-
const critic = await server.handleSwarmCoordination({
|
|
23
|
-
operation: 'register_agent',
|
|
24
|
-
name: 'SafetyCheck',
|
|
25
|
-
agentType: 'critic',
|
|
26
|
-
subtype: 'safety'
|
|
27
|
-
});
|
|
28
|
-
console.log('Registered Critic:', JSON.stringify(critic, null, 2));
|
|
29
|
-
|
|
30
|
-
// 2. Start Thinking Session
|
|
31
|
-
console.log('\n[Step 2] Initializing Thinking Session...');
|
|
32
|
-
const session = await server.handleSequentialThinking({
|
|
33
|
-
operation: 'initialize',
|
|
34
|
-
topic: 'Architecting a scalable microservices system'
|
|
35
|
-
});
|
|
36
|
-
console.log('Session Created:', JSON.stringify(session, null, 2));
|
|
37
|
-
const sessionId = session.sessionId;
|
|
38
|
-
|
|
39
|
-
// 3. Add Initial Thought
|
|
40
|
-
console.log('\n[Step 3] Adding Initial Thought...');
|
|
41
|
-
const thought1 = await server.handleSequentialThinking({
|
|
42
|
-
operation: 'add_thought',
|
|
43
|
-
sessionId: sessionId,
|
|
44
|
-
content: 'We need to break down the monolithic application into smaller services.',
|
|
45
|
-
thoughtType: 'analysis',
|
|
46
|
-
confidence: 0.8
|
|
47
|
-
});
|
|
48
|
-
console.log('Thought Added:', JSON.stringify(thought1, null, 2));
|
|
49
|
-
|
|
50
|
-
if (!thought1.thought) {
|
|
51
|
-
throw new Error('Failed to create thought');
|
|
52
|
-
}
|
|
53
|
-
const thoughtId = thought1.thought.id;
|
|
54
|
-
|
|
55
|
-
// 4. Delegate to Swarm (Reasoner)
|
|
56
|
-
console.log('\n[Step 4] Delegating to Swarm (Reasoner)...');
|
|
57
|
-
const swarmResult = await server.handleSequentialThinking({
|
|
58
|
-
operation: 'delegate_to_swarm',
|
|
59
|
-
sessionId: sessionId,
|
|
60
|
-
thoughtId: thoughtId,
|
|
61
|
-
taskType: 'reasoning',
|
|
62
|
-
requiredCapabilities: ['problem_solving']
|
|
63
|
-
});
|
|
64
|
-
console.log('Swarm Delegation Result:', JSON.stringify(swarmResult, null, 2));
|
|
65
|
-
|
|
66
|
-
// 5. Self Correction (Simulation)
|
|
67
|
-
console.log('\n[Step 5] Triggering Self-Correction...');
|
|
68
|
-
const correction = await server.handleSequentialThinking({
|
|
69
|
-
operation: 'self_correct',
|
|
70
|
-
sessionId: sessionId,
|
|
71
|
-
thoughtId: thoughtId
|
|
72
|
-
});
|
|
73
|
-
console.log('Self Correction Result:', JSON.stringify(correction, null, 2));
|
|
74
|
-
|
|
75
|
-
// 6. Complete Session
|
|
76
|
-
console.log('\n[Step 6] Completing Session...');
|
|
77
|
-
const completion = await server.handleSequentialThinking({
|
|
78
|
-
operation: 'complete_session',
|
|
79
|
-
sessionId: sessionId
|
|
80
|
-
});
|
|
81
|
-
console.log('Completion Result:', JSON.stringify(completion, null, 2));
|
|
82
|
-
|
|
83
|
-
console.log('\n--- Test Finished Successfully ---');
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
runTest().catch(error => {
|
|
87
|
-
console.error('Test Failed:', error);
|
|
88
|
-
process.exit(1);
|
|
89
|
-
});
|