@nbiish/cognitive-tools-mcp 0.9.4 → 0.9.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.
Files changed (28) hide show
  1. package/README.md +0 -31
  2. package/build/index.js +10 -7
  3. package/package.json +1 -1
  4. package/integration-prompts/new-prompts/latest.md +0 -134
  5. package/integration-prompts/old-prompts/integration-prompt-01.md +0 -71
  6. package/integration-prompts/old-prompts/integration-prompt-02.md +0 -32
  7. package/integration-prompts/old-prompts/integration-prompt-03.md +0 -71
  8. package/integration-prompts/old-prompts/integration-prompt-04.md +0 -144
  9. package/integration-prompts/old-prompts/integration-prompt-05.md +0 -84
  10. package/integration-prompts/old-prompts/integration-prompt-06.md +0 -91
  11. package/integration-prompts/old-prompts/integration-prompt-07.md +0 -88
  12. package/integration-prompts/old-prompts/integration-prompt-08.md +0 -86
  13. package/integration-prompts/old-prompts/integration-prompt-09.md +0 -86
  14. package/integration-prompts/old-prompts/integration-prompt-10.md +0 -100
  15. package/integration-prompts/old-prompts/integration-prompt-11.md +0 -79
  16. package/integration-prompts/old-prompts/integration-prompt-12.md +0 -93
  17. package/integration-prompts/old-prompts/integration-prompt-13.md +0 -81
  18. package/integration-prompts/old-prompts/integration-prompt-14.md +0 -81
  19. package/integration-prompts/old-prompts/integration-prompt-15.md +0 -80
  20. package/integration-prompts/old-prompts/integration-prompt-16.md +0 -96
  21. package/integration-tool-descriptions/old-descriptions/tool-descriptions-01.ts +0 -171
  22. package/integration-tool-descriptions/old-descriptions/tool-descriptions-02.ts +0 -216
  23. package/integration-tool-descriptions/old-descriptions/tool-descriptions-03.ts +0 -225
  24. package/integration-tool-descriptions/old-descriptions/tool-descriptions-04.ts +0 -221
  25. package/integration-tool-descriptions/old-descriptions/tool-descriptions-05.ts +0 -230
  26. package/integration-tool-descriptions/old-descriptions/tool-descriptions-06.ts +0 -506
  27. package/integration-tool-descriptions/old-descriptions/tool-descriptions-07.ts +0 -293
  28. package/integration-tool-descriptions/old-descriptions/tool-descriptions-08.ts +0 -458
@@ -1,458 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * -----------------------------------------------------------------------------
5
- * Gikendaasowin Aabajichiganan - Core Cognitive Tools MCP Server
6
- *
7
- * Version: 1.0.0
8
- *
9
- * Description: Provides a suite of cognitive tools for an AI Pair Programmer,
10
- * enabling structured reasoning, planning, analysis, and iterative
11
- * refinement (Chain of Thought, Chain of Draft, Reflection).
12
- * This server focuses on managing the AI's *internal cognitive loop*,
13
- * as described in the Anthropic research on the 'think' tool and
14
- * related cognitive patterns. External actions are planned within
15
- * the 'think' step but executed by the calling environment.
16
- *
17
- * Key Principles:
18
- * 1. **Structured Deliberation:** Tools guide specific cognitive acts (planning,
19
- * reasoning, critique).
20
- * 2. **Centralized Analysis (`think`):** The `think` tool is mandatory after
21
- * most cognitive actions or receiving external results, serving as the hub
22
- * for analysis, planning the *next immediate step*, verification, and
23
- * self-correction.
24
- * 3. **CUC-N Assessment:** Task characteristics determine the required depth
25
- * of cognition (full `think` vs. `quick_think`).
26
- * 4. **Internal Generation First:** Tools like `plan_and_solve`, `chain_of_thought`,
27
- * `reflection`, and `synthesize_prior_reasoning` are called *after* the AI
28
- * has internally generated the relevant text (plan, CoT, critique, summary).
29
- * The tool logs this generation and returns it, grounding the AI for the
30
- * mandatory `think` analysis step.
31
- * 5. **Iterative Refinement (Chain of Draft):** The `chain_of_draft` tool signals
32
- * internal draft creation/modification, prompting analysis via `think`.
33
- *
34
- * Protocol: Model Context Protocol (MCP) over stdio.
35
- * -----------------------------------------------------------------------------
36
- */
37
-
38
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
39
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
40
- import { z } from "zod";
41
-
42
- // --- Server Definition ---
43
-
44
- const server = new McpServer({
45
- name: "gikendaasowin-aabajichiganan-mcp",
46
- version: "1.0.0", // Updated version
47
- description: "ᑭᑫᓐᑖᓱᐎᓐ ᐋᐸᒋᒋᑲᓇᓐ - Core Cognitive Tools Suite v1.0.0: Enables structured, iterative reasoning (Chain of Thought/Draft), planning, and analysis for AI agents, focusing on the cognitive loop. MANDATORY `think` step integrates results."
48
- });
49
-
50
- // --- Logging Helpers ---
51
-
52
- /**
53
- * Logs an incoming tool call to stderr.
54
- * @param toolName The name of the tool being called.
55
- * @param details Optional additional details about the call.
56
- */
57
- function logToolCall(toolName: string, details?: string): void {
58
- const timestamp = new Date().toISOString();
59
- console.error(`[${timestamp}] [MCP Server] > Tool Call: ${toolName}${details ? ` - ${details}` : ''}`);
60
- }
61
-
62
- /**
63
- * Logs the result (success or failure) of a tool execution to stderr.
64
- * @param toolName The name of the tool executed.
65
- * @param success Whether the execution was successful.
66
- * @param resultDetails Optional details about the result.
67
- */
68
- function logToolResult(toolName: string, success: boolean, resultDetails?: string): void {
69
- const timestamp = new Date().toISOString();
70
- console.error(`[${timestamp}] [MCP Server] < Tool Result: ${toolName} - ${success ? 'Success' : 'Failure'}${resultDetails ? ` - ${resultDetails}` : ''}`);
71
- }
72
-
73
- /**
74
- * Logs an error during tool execution and formats a standard error response for the LLM.
75
- * @param toolName The name of the tool where the error occurred.
76
- * @param error The error object or message.
77
- * @returns An McpToolResult containing the error message.
78
- */
79
- function logToolError(toolName: string, error: unknown) {
80
- const timestamp = new Date().toISOString();
81
- const errorMessage = error instanceof Error ? error.message : String(error);
82
- console.error(`[${timestamp}] [MCP Server] ! Tool Error: ${toolName} - ${errorMessage}`);
83
- logToolResult(toolName, false, errorMessage); // Log failure result as well
84
- // Return a structured error message suitable for the LLM
85
- return {
86
- content: [{
87
- type: "text" as const,
88
- text: `Error executing tool '${toolName}': ${errorMessage}. Please analyze this error in your next 'think' step and adjust your plan.`
89
- }]
90
- };
91
- }
92
-
93
- // --- Core Cognitive Deliberation & Refinement Tools ---
94
-
95
- /**
96
- * Tool: assess_cuc_n_mode
97
- * Purpose: Mandatory initial assessment of task characteristics to determine cognitive strategy.
98
- * Workflow: Call BEFORE starting complex tasks or significantly changing strategy.
99
- * Output: Confirms assessment and selected mode (`think` or `quick_think`). Result MUST inform the subsequent cognitive flow.
100
- */
101
- server.tool(
102
- "assess_cuc_n_mode",
103
- "**Mandatory Pre-Deliberation Assessment.** Evaluates task Complexity, Uncertainty, Consequence, Novelty (CUC-N) to determine required cognitive depth and initial strategy. MUST be called before starting complex tasks or changing strategy. Selects 'think' (default) or 'quick_think' (only for verified Low CUC-N).",
104
- {
105
- assessment_and_choice: z.string().describe("Your structured assessment including: 1) Situation Description, 2) CUC-N Ratings (Low/Medium/High for each), 3) Rationale for ratings, 4) Recommended Initial Cognitive Strategy (e.g., 'Start with chain_of_thought then think'), 5) Explicit Mode Selection ('Selected Mode: think' or 'Selected Mode: quick_think').")
106
- },
107
- async ({ assessment_and_choice }) => {
108
- const toolName = 'assess_cuc_n_mode';
109
- logToolCall(toolName);
110
- try {
111
- // Enhanced validation using regex for robustness
112
- const modeRegex = /Selected Mode: (think|quick_think)/i;
113
- const cucnRegex = /CUC-N Ratings:/i;
114
- const strategyRegex = /Recommended Initial Strategy:/i;
115
-
116
- if (!assessment_and_choice || typeof assessment_and_choice !== 'string') {
117
- throw new Error('Input must be a non-empty string.');
118
- }
119
- if (!cucnRegex.test(assessment_and_choice)) {
120
- throw new Error('Invalid assessment: String must include "CUC-N Ratings:".');
121
- }
122
- if (!strategyRegex.test(assessment_and_choice)) {
123
- throw new Error('Invalid assessment: String must include "Recommended Initial Strategy:".');
124
- }
125
- const modeMatch = assessment_and_choice.match(modeRegex);
126
- if (!modeMatch || !modeMatch[1]) {
127
- throw new Error('Invalid assessment: String must include explicit "Selected Mode: think" or "Selected Mode: quick_think".');
128
- }
129
-
130
- const selectedMode = modeMatch[1].toLowerCase();
131
- const resultText = `Cognitive Assessment Completed. CUC-N analysis indicates ${selectedMode === 'think' ? 'detailed deliberation' : 'quick check'} is appropriate. Proceeding with selected mode: ${selectedMode}. Full Assessment logged. Ensure subsequent actions align with this assessment.`;
132
- logToolResult(toolName, true, `Selected mode: ${selectedMode}`);
133
- // Log the full assessment server-side for traceability
134
- console.error(`[${new Date().toISOString()}] [MCP Server] - ${toolName} Assessment Details:\n${assessment_and_choice}`);
135
- return { content: [{ type: "text" as const, text: resultText }] };
136
- } catch (error: unknown) {
137
- return logToolError(toolName, error);
138
- }
139
- }
140
- );
141
-
142
- /**
143
- * Tool: think
144
- * Purpose: The **CENTRAL HUB** for the cognitive loop. Mandatory after assessment, other cognitive tools, internal drafts, or external action results.
145
- * Workflow: Analyze previous step -> Plan immediate next step -> Verify -> Assess Risk -> Self-Correct.
146
- * Output: Returns the structured thought text itself, grounding the AI's reasoning process in the context.
147
- */
148
- server.tool(
149
- "think",
150
- "**MANDATORY Central Hub for Analysis, Planning, and Refinement.** Called after assessment, other cognitive tools (`plan_and_solve`, `chain_of_thought`, etc.), internal drafts (`chain_of_draft`), or external action results. Analyzes previous step's outcome/draft, plans the *immediate* next action (cognitive or planning external action), verifies plan, assesses risk/challenges, looks ahead, and self-corrects. Follow the MANDATORY structure in the `thought` parameter.",
151
- {
152
- thought: z.string().describe("Your **detailed** internal monologue following the MANDATORY structure: ## Analysis: (Critically evaluate last result/draft/observation. What worked? What didn't? What are the implications?), ## Plan: (Define the *single, immediate* next action and its specific purpose. Is it calling another cognitive tool, generating a draft, planning an external action, or concluding?), ## Verification: (How will you confirm the next step is correct or successful?), ## Anticipated Challenges & Contingency: (What could go wrong with the next step? How will you handle it?), ## Risk Assessment: (Briefly assess risk of the planned step - Low/Medium/High), ## Lookahead: (How does this step fit into the overall goal?), ## Self-Correction & Learning: (Any adjustments needed based on the analysis? What was learned?).")
153
- },
154
- async ({ thought }) => {
155
- const toolName = 'think';
156
- logToolCall(toolName);
157
- try {
158
- if (!thought || typeof thought !== 'string' || thought.trim().length === 0) {
159
- throw new Error('Invalid thought: Must be a non-empty string containing the structured analysis and plan.');
160
- }
161
- // Basic structural check (case-insensitive) - Warning, not strict failure
162
- const requiredSections = ["## Analysis:", "## Plan:", "## Verification:", "## Anticipated Challenges & Contingency:", "## Risk Assessment:", "## Lookahead:", "## Self-Correction & Learning:"];
163
- const missingSections = requiredSections.filter(section => !thought.toLowerCase().includes(section.toLowerCase()));
164
- if (missingSections.length > 0) {
165
- console.warn(`[${new Date().toISOString()}] [MCP Server] Warning: '${toolName}' input might be missing sections: ${missingSections.join(', ')}. Ensure full structure is followed for optimal reasoning.`);
166
- }
167
-
168
- logToolResult(toolName, true, `Thought logged (length: ${thought.length})`);
169
- // Returns the same thought text received. This grounds the reasoning in the context.
170
- // The AI uses this output implicitly as the starting point for its *next* internal step or external action.
171
- return { content: [{ type: "text" as const, text: thought }] };
172
- } catch (error: unknown) {
173
- return logToolError(toolName, error);
174
- }
175
- }
176
- );
177
-
178
- /**
179
- * Tool: quick_think
180
- * Purpose: A lightweight cognitive checkpoint for **strictly Low CUC-N situations** or trivial confirmations.
181
- * Workflow: Use ONLY when `assess_cuc_n_mode` explicitly selected 'quick_think'. Use sparingly.
182
- * Output: Logs the brief thought.
183
- */
184
- server.tool(
185
- "quick_think",
186
- "Cognitive Checkpoint ONLY for situations explicitly assessed as strictly Low CUC-N (via `assess_cuc_n_mode`) or for trivial confirmations/acknowledgements where detailed analysis via `think` is unnecessary. Use SPARINGLY.",
187
- {
188
- brief_thought: z.string().describe("Your **concise** thought or confirmation for this simple, low CUC-N step. Briefly state the observation/action and confirm it's trivial.")
189
- },
190
- async ({ brief_thought }) => {
191
- const toolName = 'quick_think';
192
- logToolCall(toolName);
193
- try {
194
- if (!brief_thought || typeof brief_thought !== 'string' || brief_thought.trim().length === 0) {
195
- throw new Error('Invalid brief_thought: Must be a non-empty string.');
196
- }
197
- logToolResult(toolName, true, `Logged: ${brief_thought.substring(0, 80)}...`);
198
- // Returns the brief thought, similar to 'think', for grounding.
199
- return { content: [{ type: "text" as const, text: brief_thought }] };
200
- } catch (error: unknown) {
201
- return logToolError(toolName, error);
202
- }
203
- }
204
- );
205
-
206
- /**
207
- * Tool: gauge_confidence
208
- * Purpose: Meta-Cognitive Checkpoint to explicitly state confidence in a preceding analysis, plan, or draft.
209
- * Workflow: Generate assessment -> Call this tool with assessment text -> MANDATORY `think` step follows to analyze the confidence level.
210
- * Output: Confirms confidence gauging and level. Emphasizes need for `think` analysis, especially if not High.
211
- */
212
- server.tool(
213
- "gauge_confidence",
214
- "Meta-Cognitive Checkpoint. Guides *internal stating* of **confidence (High/Medium/Low) and justification** regarding a specific plan, analysis, or draft you just formulated. Call this tool *with* the text containing your confidence assessment. Output MUST be analyzed in the mandatory `think` step immediately following.",
215
- {
216
- assessment_and_confidence: z.string().describe("The text containing the item being assessed AND your explicit internal assessment: 1) Confidence Level: (High/Medium/Low). 2) Justification for this level.")
217
- },
218
- async ({ assessment_and_confidence }) => {
219
- const toolName = 'gauge_confidence';
220
- logToolCall(toolName);
221
- try {
222
- const confidenceRegex = /Confidence Level: (High|Medium|Low)/i;
223
- if (!assessment_and_confidence || typeof assessment_and_confidence !== 'string') {
224
- throw new Error('Input must be a non-empty string.');
225
- }
226
- const match = assessment_and_confidence.match(confidenceRegex);
227
- if (!match || !match[1]) {
228
- throw new Error('Invalid confidence assessment: String must include "Confidence Level: High/Medium/Low" and justification.');
229
- }
230
-
231
- const level = match[1];
232
- const emphasis = (level.toLowerCase() !== 'high') ? "CRITICAL: Analyze implications of non-High confidence." : "Proceed with analysis.";
233
- const resultText = `Confidence Gauge Completed. Stated Level: ${level}. Assessment Text Logged. MANDATORY: Analyze this confidence level and justification in your next 'think' step. ${emphasis}`;
234
- logToolResult(toolName, true, `Level: ${level}`);
235
- console.error(`[${new Date().toISOString()}] [MCP Server] - ${toolName} Confidence Details:\n${assessment_and_confidence}`);
236
- return { content: [{ type: "text" as const, text: resultText }] };
237
- } catch (error: unknown) {
238
- return logToolError(toolName, error);
239
- }
240
- }
241
- );
242
-
243
- /**
244
- * Tool: plan_and_solve
245
- * Purpose: Guides the *internal generation* of a structured plan draft.
246
- * Workflow: Internally generate plan -> Call this tool *with* the plan text -> MANDATORY `think` step follows to analyze/refine the plan.
247
- * Output: Returns the provided plan text for grounding and analysis.
248
- */
249
- server.tool(
250
- "plan_and_solve",
251
- "Guides *internal generation* of a **structured plan draft**. Call this tool *with* the generated plan text you created internally. Returns the plan text. MANDATORY: Use the next `think` step to critically evaluate this plan's feasibility, refine it, and confirm the *first actionable step*.",
252
- {
253
- generated_plan_text: z.string().describe("The **full, structured plan draft** you generated internally, including goals, steps, potential external tool needs, assumptions, and risks."),
254
- task_objective: z.string().describe("The original high-level task objective this plan addresses.")
255
- },
256
- async ({ generated_plan_text, task_objective }) => {
257
- const toolName = 'plan_and_solve';
258
- logToolCall(toolName, `Objective: ${task_objective.substring(0, 80)}...`);
259
- try {
260
- if (!generated_plan_text || typeof generated_plan_text !== 'string' || generated_plan_text.trim().length === 0) {
261
- throw new Error('Invalid generated_plan_text: Must be a non-empty string containing the plan.');
262
- }
263
- if (!task_objective || typeof task_objective !== 'string' || task_objective.trim().length === 0) {
264
- throw new Error('Invalid task_objective: Must provide the original objective.');
265
- }
266
- logToolResult(toolName, true, `Returned plan draft for analysis (length: ${generated_plan_text.length})`);
267
- // Returns the actual plan text received. The AI must analyze this in the next 'think' step.
268
- return { content: [{ type: "text" as const, text: generated_plan_text }] };
269
- } catch (error: unknown) {
270
- return logToolError(toolName, error);
271
- }
272
- }
273
- );
274
-
275
- /**
276
- * Tool: chain_of_thought
277
- * Purpose: Guides the *internal generation* of a detailed, step-by-step reasoning draft (CoT).
278
- * Workflow: Internally generate CoT -> Call this tool *with* the CoT text -> MANDATORY `think` step follows to analyze the reasoning.
279
- * Output: Returns the provided CoT text for grounding and analysis.
280
- */
281
- server.tool(
282
- "chain_of_thought",
283
- "Guides *internal generation* of **detailed, step-by-step reasoning draft (CoT)**. Call this tool *with* the generated CoT text you created internally. Returns the CoT text. MANDATORY: Use the next `think` step to analyze this reasoning, extract insights, identify flaws/gaps, and plan the next concrete action based on the CoT.",
284
- {
285
- generated_cot_text: z.string().describe("The **full, step-by-step Chain of Thought draft** you generated internally to solve or analyze the problem."),
286
- problem_statement: z.string().describe("The original problem statement or question this CoT addresses.")
287
- },
288
- async ({ generated_cot_text, problem_statement }) => {
289
- const toolName = 'chain_of_thought';
290
- logToolCall(toolName, `Problem: ${problem_statement.substring(0, 80)}...`);
291
- try {
292
- if (!generated_cot_text || typeof generated_cot_text !== 'string' || generated_cot_text.trim().length === 0) {
293
- throw new Error('Invalid generated_cot_text: Must be a non-empty string containing the CoT.');
294
- }
295
- if (!problem_statement || typeof problem_statement !== 'string' || problem_statement.trim().length === 0) {
296
- throw new Error('Invalid problem_statement: Must provide the original problem.');
297
- }
298
- logToolResult(toolName, true, `Returned CoT draft for analysis (length: ${generated_cot_text.length})`);
299
- // Returns the actual CoT text received. The AI must analyze this in the next 'think' step.
300
- return { content: [{ type: "text" as const, text: generated_cot_text }] };
301
- } catch (error: unknown) {
302
- return logToolError(toolName, error);
303
- }
304
- }
305
- );
306
-
307
- /**
308
- * Tool: chain_of_draft
309
- * Purpose: Signals that internal drafts (code, text, plan fragments) have been generated or refined.
310
- * Workflow: Internally generate/refine draft(s) -> Call this tool -> MANDATORY `think` step follows to analyze the draft(s).
311
- * Output: Confirms readiness for analysis.
312
- */
313
- server.tool(
314
- "chain_of_draft",
315
- "Signals that one or more **internal drafts** (e.g., code snippets, documentation sections, refined plan steps) have been generated or refined and are ready for analysis. Call this tool *after* generating/refining draft(s) internally. Response confirms readiness. MANDATORY: Analyze these draft(s) in your next `think` step.",
316
- {
317
- draft_description: z.string().describe("Brief but specific description of the draft(s) generated/refined internally (e.g., 'Initial Python function for API call', 'Refined error handling in plan step 3', 'Drafted README introduction').")
318
- },
319
- async ({ draft_description }) => {
320
- const toolName = 'chain_of_draft';
321
- logToolCall(toolName, `Description: ${draft_description}`);
322
- try {
323
- if (!draft_description || typeof draft_description !== 'string' || draft_description.trim().length === 0) {
324
- throw new Error('Invalid draft_description: Must provide a description.');
325
- }
326
- const resultText = `Internal draft(s) ready for analysis: "${draft_description}". MANDATORY: Analyze these draft(s) now using the structured format in your next 'think' step. Evaluate correctness, completeness, and alignment with goals.`;
327
- logToolResult(toolName, true);
328
- return { content: [{ type: "text" as const, text: resultText }] };
329
- } catch (error: unknown) {
330
- return logToolError(toolName, error);
331
- }
332
- }
333
- );
334
-
335
- /**
336
- * Tool: reflection
337
- * Purpose: Guides the *internal generation* of a critical self-evaluation (critique) of a prior step, draft, or outcome.
338
- * Workflow: Internally generate critique -> Call this tool *with* the critique text -> MANDATORY `think` step follows to act on the critique.
339
- * Output: Returns the provided critique text for grounding and analysis.
340
- */
341
- server.tool(
342
- "reflection",
343
- "Guides *internal generation* of a critical self-evaluation (critique) on a prior step, draft, plan, or outcome. Call this tool *with* the **generated critique text** you created internally. Returns the critique text. MANDATORY: Use the next `think` step to analyze this critique and plan specific corrective actions or refinements based on it.",
344
- {
345
- generated_critique_text: z.string().describe("The **full critique text** you generated internally, identifying specific flaws, strengths, assumptions, alternative approaches, and concrete suggestions for improvement."),
346
- input_subject_description: z.string().describe("A brief description of the original reasoning, plan, code draft, or action result that was critiqued (e.g., 'Critique of the plan generated via plan_and_solve', 'Reflection on the CoT for problem X').")
347
- },
348
- async ({ generated_critique_text, input_subject_description }) => {
349
- const toolName = 'reflection';
350
- logToolCall(toolName, `Subject: ${input_subject_description}`);
351
- try {
352
- if (!generated_critique_text || typeof generated_critique_text !== 'string' || generated_critique_text.trim().length === 0) {
353
- throw new Error('Invalid generated_critique_text: Must be a non-empty string containing the critique.');
354
- }
355
- if (!input_subject_description || typeof input_subject_description !== 'string' || input_subject_description.trim().length === 0) {
356
- throw new Error('Invalid input_subject_description: Must describe what was critiqued.');
357
- }
358
- logToolResult(toolName, true, `Returned critique for analysis (length: ${generated_critique_text.length})`);
359
- // Returns the actual critique text received. The AI must analyze this in the next 'think' step.
360
- return { content: [{ type: "text" as const, text: generated_critique_text }] };
361
- } catch (error: unknown) {
362
- return logToolError(toolName, error);
363
- }
364
- }
365
- );
366
-
367
- /**
368
- * Tool: synthesize_prior_reasoning
369
- * Purpose: Context Management Tool. Guides the *internal generation* of a structured summary of preceding context.
370
- * Workflow: Internally generate summary -> Call this tool *with* the summary text -> MANDATORY `think` step follows to use the summary.
371
- * Output: Returns the provided summary text for grounding and analysis.
372
- */
373
- server.tool(
374
- "synthesize_prior_reasoning",
375
- "Context Management Tool. Guides *internal generation* of a **structured summary** of preceding steps, decisions, key findings, or relevant context to consolidate understanding before proceeding. Call this tool *with* the generated summary text you created internally. Returns the summary. MANDATORY: Use the next `think` step to leverage this summary and inform the next action.",
376
- {
377
- generated_summary_text: z.string().describe("The **full, structured summary text** you generated internally (e.g., key decisions made, open questions, current state of implementation, relevant facts gathered)."),
378
- context_to_summarize_description: z.string().describe("Description of the reasoning span or context that was summarized (e.g., 'Summary of the last 5 steps', 'Consolidated findings from tool results A and B').")
379
- },
380
- async ({ generated_summary_text, context_to_summarize_description }) => {
381
- const toolName = 'synthesize_prior_reasoning';
382
- logToolCall(toolName, `Context: ${context_to_summarize_description}`);
383
- try {
384
- if (!generated_summary_text || typeof generated_summary_text !== 'string' || generated_summary_text.trim().length === 0) {
385
- throw new Error('Invalid generated_summary_text: Must be a non-empty string containing the summary.');
386
- }
387
- if (!context_to_summarize_description || typeof context_to_summarize_description !== 'string' || context_to_summarize_description.trim().length === 0) {
388
- throw new Error('Invalid context_to_summarize_description: Must describe what was summarized.');
389
- }
390
- logToolResult(toolName, true, `Returned summary for analysis (length: ${generated_summary_text.length})`);
391
- // Returns the actual summary text received. The AI must analyze/use this in the next 'think' step.
392
- return { content: [{ type: "text" as const, text: generated_summary_text }] };
393
- } catch (error: unknown) {
394
- return logToolError(toolName, error);
395
- }
396
- }
397
- );
398
-
399
-
400
- // --- Server Lifecycle and Error Handling ---
401
-
402
- /**
403
- * Gracefully shuts down the server.
404
- */
405
- async function shutdown(): Promise<void> {
406
- console.error('\n[MCP Server] Shutting down gracefully...');
407
- try {
408
- await server.close();
409
- console.error('[MCP Server] Server closed.');
410
- process.exit(0);
411
- } catch (err) {
412
- console.error('[MCP Server] Error during shutdown:', err);
413
- process.exit(1);
414
- }
415
- }
416
-
417
- process.on('SIGINT', shutdown);
418
- process.on('SIGTERM', shutdown);
419
-
420
- process.on('uncaughtException', (error, origin) => {
421
- const timestamp = new Date().toISOString();
422
- console.error(`[${timestamp}] [MCP Server] FATAL: Uncaught Exception at: ${origin}`, error);
423
- // Attempt graceful shutdown, but exit quickly if it fails
424
- shutdown().catch(() => process.exit(1));
425
- });
426
-
427
- process.on('unhandledRejection', (reason, promise) => {
428
- const timestamp = new Date().toISOString();
429
- console.error(`[${timestamp}] [MCP Server] FATAL: Unhandled Promise Rejection:`, reason);
430
- // Attempt graceful shutdown, but exit quickly if it fails
431
- shutdown().catch(() => process.exit(1));
432
- });
433
-
434
- // --- Start the Server ---
435
-
436
- /**
437
- * Initializes and starts the MCP server.
438
- */
439
- async function main(): Promise<void> {
440
- try {
441
- const transport = new StdioServerTransport();
442
- await server.connect(transport);
443
- const border = '-----------------------------------------------------';
444
- console.error(border);
445
- console.error(` ᑭᑫᓐᑖᓱᐎᓐ ᐋᐸᒋᒋᑲᓇᓐ - Core Cognitive Tools Suite v1.0.0: Enables structured, iterative reasoning (Chain of Thought/Draft), planning, and analysis for AI agents, focusing on the cognitive loop. MANDATORY \`think\` step integrates results.`);
446
- console.error(` Version: 1.0.0`);
447
- console.error(' Status: Running on stdio, awaiting MCP requests...');
448
- console.error(border);
449
- }
450
- catch (error) {
451
- const timestamp = new Date().toISOString();
452
- console.error(`[${timestamp}] [MCP Server] Fatal error during startup:`, error);
453
- process.exit(1);
454
- }
455
- }
456
-
457
- // Execute the main function to start the server
458
- main();