@nbiish/cognitive-tools-mcp 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,7 +26,7 @@ Known as:
26
26
 
27
27
  Both packages are maintained in parallel and receive the same updates. You can use either package name in your projects - they provide identical functionality.
28
28
 
29
- **See the latest integration details in [`integration-prompts/integration-prompt-07.md`](integration-prompts/integration-prompt-07.md).**
29
+ **See the latest integration details in [`integration-prompts/new-prompts/latest.md`](integration-prompts/new-prompts/latest.md).**
30
30
 
31
31
  ## Features
32
32
 
package/build/index.js CHANGED
@@ -3,244 +3,389 @@
3
3
  * -----------------------------------------------------------------------------
4
4
  * Gikendaasowin Aabajichiganan - Core Cognitive Tools MCP Server
5
5
  *
6
- * Description: Provides the essential suite of cognitive tools for an AI
7
- * Pair Programmer to structure its reasoning, plan actions,
8
- * analyze results, and iteratively refine its work, focusing on
9
- * the internal cognitive loop as described in the corresponding
10
- * integration prompt. External actions are planned within 'think'
11
- * but executed by the environment.
6
+ * Version: 0.9.4
7
+ *
8
+ * Description: Provides a suite of cognitive tools for an AI Pair Programmer,
9
+ * enabling structured reasoning, planning, analysis, and iterative
10
+ * refinement (Chain of Thought, Chain of Draft, Reflection).
11
+ * This server focuses on managing the AI's *internal cognitive loop*,
12
+ * as described in the Anthropic research on the 'think' tool and
13
+ * related cognitive patterns. External actions are planned within
14
+ * the 'think' step but executed by the calling environment.
15
+ *
16
+ * Key Principles:
17
+ * 1. **Structured Deliberation:** Tools guide specific cognitive acts (planning,
18
+ * reasoning, critique).
19
+ * 2. **Centralized Analysis (`think`):** The `think` tool is mandatory after
20
+ * most cognitive actions or receiving external results, serving as the hub
21
+ * for analysis, planning the *next immediate step*, verification, and
22
+ * self-correction.
23
+ * 3. **CUC-N Assessment:** Task characteristics determine the required depth
24
+ * of cognition (full `think` vs. `quick_think`).
25
+ * 4. **Internal Generation First:** Tools like `plan_and_solve`, `chain_of_thought`,
26
+ * `reflection`, and `synthesize_prior_reasoning` are called *after* the AI
27
+ * has internally generated the relevant text (plan, CoT, critique, summary).
28
+ * The tool logs this generation and returns it, grounding the AI for the
29
+ * mandatory `think` analysis step.
30
+ * 5. **Iterative Refinement (Chain of Draft):** The `chain_of_draft` tool signals
31
+ * internal draft creation/modification, prompting analysis via `think`.
32
+ *
12
33
  * Protocol: Model Context Protocol (MCP) over stdio.
13
34
  * -----------------------------------------------------------------------------
14
35
  */
15
36
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
37
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
17
38
  import { z } from "zod";
39
+ export const version = "0.9.4";
18
40
  // --- Server Definition ---
19
41
  const server = new McpServer({
20
42
  name: "gikendaasowin-aabajichiganan-mcp",
21
- version: "0.9.2",
22
- description: "ᑭᑫᓐᑖᓱᐎᓐ ᐋᐸᒋᒋᑲᓇᓐ - Core Cognitive Tools Suite: Enables structured, iterative reasoning (Chain of Draft), planning, and analysis for AI Pair Programming, focusing on the cognitive loop."
43
+ version: version,
44
+ description: "ᑭᑫᓐᑖᓱᐎᓐ ᐋᐸᒋᒋᑲᓇᓐ - Core Cognitive Tools Suite v0.9.4: Enables structured, iterative reasoning (Chain of Thought/Draft), planning, and analysis for AI agents, focusing on the cognitive loop. MANDATORY `think` step integrates results."
23
45
  });
24
- // --- Logging Helper ---
46
+ // --- Logging Helpers ---
47
+ /**
48
+ * Logs an incoming tool call to stderr.
49
+ * @param toolName The name of the tool being called.
50
+ * @param details Optional additional details about the call.
51
+ */
25
52
  function logToolCall(toolName, details) {
26
- console.error(`[MCP Server] > Tool Call: ${toolName}${details ? ` - ${details}` : ''}`);
53
+ const timestamp = new Date().toISOString();
54
+ console.error(`[${timestamp}] [MCP Server] > Tool Call: ${toolName}${details ? ` - ${details}` : ''}`);
27
55
  }
56
+ /**
57
+ * Logs the result (success or failure) of a tool execution to stderr.
58
+ * @param toolName The name of the tool executed.
59
+ * @param success Whether the execution was successful.
60
+ * @param resultDetails Optional details about the result.
61
+ */
28
62
  function logToolResult(toolName, success, resultDetails) {
29
- console.error(`[MCP Server] < Tool Result: ${toolName} - ${success ? 'Success' : 'Failure'}${resultDetails ? ` - ${resultDetails}` : ''}`);
63
+ const timestamp = new Date().toISOString();
64
+ console.error(`[${timestamp}] [MCP Server] < Tool Result: ${toolName} - ${success ? 'Success' : 'Failure'}${resultDetails ? ` - ${resultDetails}` : ''}`);
30
65
  }
66
+ /**
67
+ * Logs an error during tool execution and formats a standard error response for the LLM.
68
+ * @param toolName The name of the tool where the error occurred.
69
+ * @param error The error object or message.
70
+ * @returns An McpToolResult containing the error message.
71
+ */
31
72
  function logToolError(toolName, error) {
73
+ const timestamp = new Date().toISOString();
32
74
  const errorMessage = error instanceof Error ? error.message : String(error);
33
- console.error(`[MCP Server] ! Tool Error: ${toolName} - ${errorMessage}`);
75
+ console.error(`[${timestamp}] [MCP Server] ! Tool Error: ${toolName} - ${errorMessage}`);
34
76
  logToolResult(toolName, false, errorMessage); // Log failure result as well
35
77
  // Return a structured error message suitable for the LLM
36
- return { content: [{ type: "text", text: `Error in ${toolName}: ${errorMessage}` }] };
78
+ return {
79
+ content: [{
80
+ type: "text",
81
+ text: `Error executing tool '${toolName}': ${errorMessage}. Please analyze this error in your next 'think' step and adjust your plan.`
82
+ }]
83
+ };
37
84
  }
38
85
  // --- Core Cognitive Deliberation & Refinement Tools ---
39
- server.tool("assess_cuc_n_mode", "**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.", {
40
- assessment_and_choice: z.string().describe("Structured assessment including: 1) Situation Description, 2) CUC-N Ratings (L/M/H), 3) Recommended Initial Cognitive Strategy (e.g., 'Start with chain_of_thought'), 4) Explicit Mode Selection ('Selected Mode: think' or 'Selected Mode: quick_think').")
86
+ /**
87
+ * Tool: assess_cuc_n_mode
88
+ * Purpose: Mandatory initial assessment of task characteristics to determine cognitive strategy.
89
+ * Workflow: Call BEFORE starting complex tasks or significantly changing strategy.
90
+ * Output: Confirms assessment and selected mode (`think` or `quick_think`). Result MUST inform the subsequent cognitive flow.
91
+ */
92
+ server.tool("assess_cuc_n_mode", "**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).", {
93
+ 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').")
41
94
  }, async ({ assessment_and_choice }) => {
42
- logToolCall('assess_cuc_n_mode');
95
+ const toolName = 'assess_cuc_n_mode';
96
+ logToolCall(toolName);
43
97
  try {
44
- // Basic validation for required components
45
- if (!assessment_and_choice.includes("Selected Mode:") || !assessment_and_choice.includes("CUC-N Ratings:") || !assessment_and_choice.includes("Recommended Initial Strategy:")) {
46
- throw new Error('Invalid assessment: String must include CUC-N ratings, Recommended Initial Strategy, and explicit Selected Mode.');
98
+ // Enhanced validation using regex for robustness
99
+ const modeRegex = /Selected Mode: (think|quick_think)/i;
100
+ const cucnRegex = /CUC-N Ratings:/i;
101
+ const strategyRegex = /Recommended Initial Strategy:/i;
102
+ if (!assessment_and_choice || typeof assessment_and_choice !== 'string') {
103
+ throw new Error('Input must be a non-empty string.');
104
+ }
105
+ if (!cucnRegex.test(assessment_and_choice)) {
106
+ throw new Error('Invalid assessment: String must include "CUC-N Ratings:".');
47
107
  }
48
- const mode = assessment_and_choice.includes("Selected Mode: think") ? "think" : "quick_think";
49
- const resultText = `Cognitive Assessment Completed. Proceeding with selected mode: ${mode}. Full Assessment:\n${assessment_and_choice}`;
50
- logToolResult('assess_cuc_n_mode', true, `Selected mode: ${mode}`);
108
+ if (!strategyRegex.test(assessment_and_choice)) {
109
+ throw new Error('Invalid assessment: String must include "Recommended Initial Strategy:".');
110
+ }
111
+ const modeMatch = assessment_and_choice.match(modeRegex);
112
+ if (!modeMatch || !modeMatch[1]) {
113
+ throw new Error('Invalid assessment: String must include explicit "Selected Mode: think" or "Selected Mode: quick_think".');
114
+ }
115
+ const selectedMode = modeMatch[1].toLowerCase();
116
+ 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.`;
117
+ logToolResult(toolName, true, `Selected mode: ${selectedMode}`);
118
+ // Log the full assessment server-side for traceability
119
+ console.error(`[${new Date().toISOString()}] [MCP Server] - ${toolName} Assessment Details:\n${assessment_and_choice}`);
51
120
  return { content: [{ type: "text", text: resultText }] };
52
121
  }
53
122
  catch (error) {
54
- return logToolError('assess_cuc_n_mode', error);
123
+ return logToolError(toolName, error);
55
124
  }
56
125
  });
57
- server.tool("think", "**MANDATORY Central Hub for Analysis, Planning, and Refinement.** Called after assessment, cognitive tools, internal drafts, or external action results. Analyzes previous step's outcome/draft, plans immediate next action (cognitive or planning external action), verifies, assesses risk, and self-corrects. Returns the thought text for grounding.", {
58
- thought: z.string().describe("Your **detailed** internal monologue following the MANDATORY structure: ## Analysis (critically evaluate last result/draft), ## Plan (define *immediate* next action & purpose - cognitive or planning external), ## Verification (how to check next step), ## Anticipated Challenges & Contingency, ## Risk Assessment, ## Lookahead, ## Self-Correction & Learning.")
126
+ /**
127
+ * Tool: think
128
+ * Purpose: The **CENTRAL HUB** for the cognitive loop. Mandatory after assessment, other cognitive tools, internal drafts, or external action results.
129
+ * Workflow: Analyze previous step -> Plan immediate next step -> Verify -> Assess Risk -> Self-Correct.
130
+ * Output: Returns the structured thought text itself, grounding the AI's reasoning process in the context.
131
+ */
132
+ server.tool("think", "**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.", {
133
+ 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?).")
59
134
  }, async ({ thought }) => {
60
- logToolCall('think');
135
+ const toolName = 'think';
136
+ logToolCall(toolName);
61
137
  try {
62
138
  if (!thought || typeof thought !== 'string' || thought.trim().length === 0) {
63
- throw new Error('Invalid thought: Must be a non-empty string.');
139
+ throw new Error('Invalid thought: Must be a non-empty string containing the structured analysis and plan.');
64
140
  }
65
- // Basic check for mandatory sections
141
+ // Basic structural check (case-insensitive) - Warning, not strict failure
66
142
  const requiredSections = ["## Analysis:", "## Plan:", "## Verification:", "## Anticipated Challenges & Contingency:", "## Risk Assessment:", "## Lookahead:", "## Self-Correction & Learning:"];
67
- const missingSections = requiredSections.filter(section => !thought.includes(section));
143
+ const missingSections = requiredSections.filter(section => !thought.toLowerCase().includes(section.toLowerCase()));
68
144
  if (missingSections.length > 0) {
69
- console.warn(`[MCP Server] Warning: 'think' input might be missing sections: ${missingSections.join(', ')}`);
145
+ console.warn(`[${new Date().toISOString()}] [MCP Server] Warning: '${toolName}' input might be missing sections: ${missingSections.join(', ')}. Ensure full structure is followed for optimal reasoning.`);
70
146
  }
71
- logToolResult('think', true, `Thought logged (length: ${thought.length})`);
72
- // Returns the same thought text received.
147
+ logToolResult(toolName, true, `Thought logged (length: ${thought.length})`);
148
+ // Returns the same thought text received. This grounds the reasoning in the context.
149
+ // The AI uses this output implicitly as the starting point for its *next* internal step or external action.
73
150
  return { content: [{ type: "text", text: thought }] };
74
151
  }
75
152
  catch (error) {
76
- return logToolError('think', error);
153
+ return logToolError(toolName, error);
77
154
  }
78
155
  });
79
- server.tool("quick_think", "Cognitive Checkpoint ONLY for situations explicitly assessed as strictly Low CUC-N (via assess_cuc_n_mode) or for trivial confirmations where detailed analysis via `think` is unnecessary. Use sparingly.", {
80
- brief_thought: z.string().describe("Your **concise** thought for strictly simple, low CUC-N situations or brief confirmations.")
156
+ /**
157
+ * Tool: quick_think
158
+ * Purpose: A lightweight cognitive checkpoint for **strictly Low CUC-N situations** or trivial confirmations.
159
+ * Workflow: Use ONLY when `assess_cuc_n_mode` explicitly selected 'quick_think'. Use sparingly.
160
+ * Output: Logs the brief thought.
161
+ */
162
+ server.tool("quick_think", "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.", {
163
+ 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.")
81
164
  }, async ({ brief_thought }) => {
82
- logToolCall('quick_think');
165
+ const toolName = 'quick_think';
166
+ logToolCall(toolName);
83
167
  try {
84
168
  if (!brief_thought || typeof brief_thought !== 'string' || brief_thought.trim().length === 0) {
85
- throw new Error('Invalid brief_thought: Must be non-empty.');
169
+ throw new Error('Invalid brief_thought: Must be a non-empty string.');
86
170
  }
87
- logToolResult('quick_think', true, `Logged: ${brief_thought.substring(0, 50)}...`);
88
- return { content: [{ type: "text", text: `Quick Thought logged successfully.` }] };
171
+ logToolResult(toolName, true, `Logged: ${brief_thought.substring(0, 80)}...`);
172
+ // Returns the brief thought, similar to 'think', for grounding.
173
+ return { content: [{ type: "text", text: brief_thought }] };
89
174
  }
90
175
  catch (error) {
91
- return logToolError('quick_think', error);
176
+ return logToolError(toolName, error);
92
177
  }
93
178
  });
94
- server.tool("gauge_confidence", "Meta-Cognitive Checkpoint. Guides internal stating of **confidence (High/Medium/Low) and justification** regarding a plan, analysis, or draft. Output MUST be analyzed in the mandatory `think` step immediately after.", {
95
- assessment_and_confidence: z.string().describe("Input item being assessed. *Internally determine and state*: 1) Confidence Level (H/M/L). 2) Justification. Call this tool *after* making the assessment.")
179
+ /**
180
+ * Tool: gauge_confidence
181
+ * Purpose: Meta-Cognitive Checkpoint to explicitly state confidence in a preceding analysis, plan, or draft.
182
+ * Workflow: Generate assessment -> Call this tool with assessment text -> MANDATORY `think` step follows to analyze the confidence level.
183
+ * Output: Confirms confidence gauging and level. Emphasizes need for `think` analysis, especially if not High.
184
+ */
185
+ server.tool("gauge_confidence", "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.", {
186
+ 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.")
96
187
  }, async ({ assessment_and_confidence }) => {
97
- logToolCall('gauge_confidence');
188
+ const toolName = 'gauge_confidence';
189
+ logToolCall(toolName);
98
190
  try {
99
191
  const confidenceRegex = /Confidence Level: (High|Medium|Low)/i;
100
- if (!assessment_and_confidence || typeof assessment_and_confidence !== 'string' || !confidenceRegex.test(assessment_and_confidence)) {
101
- throw new Error('Invalid confidence assessment: String must include "Confidence Level: High/Medium/Low" and justification.');
192
+ if (!assessment_and_confidence || typeof assessment_and_confidence !== 'string') {
193
+ throw new Error('Input must be a non-empty string.');
102
194
  }
103
195
  const match = assessment_and_confidence.match(confidenceRegex);
104
- const level = match ? match[1] : "Unknown";
105
- const resultText = `Confidence Gauge Completed. Level: ${level}. Assessment Text: ${assessment_and_confidence}. Ready for mandatory post-assessment 'think' analysis (action required if Low/Medium).`;
106
- logToolResult('gauge_confidence', true, `Level: ${level}`);
196
+ if (!match || !match[1]) {
197
+ throw new Error('Invalid confidence assessment: String must include "Confidence Level: High/Medium/Low" and justification.');
198
+ }
199
+ const level = match[1];
200
+ const emphasis = (level.toLowerCase() !== 'high') ? "CRITICAL: Analyze implications of non-High confidence." : "Proceed with analysis.";
201
+ const resultText = `Confidence Gauge Completed. Stated Level: ${level}. Assessment Text Logged. MANDATORY: Analyze this confidence level and justification in your next 'think' step. ${emphasis}`;
202
+ logToolResult(toolName, true, `Level: ${level}`);
203
+ console.error(`[${new Date().toISOString()}] [MCP Server] - ${toolName} Confidence Details:\n${assessment_and_confidence}`);
107
204
  return { content: [{ type: "text", text: resultText }] };
108
205
  }
109
206
  catch (error) {
110
- return logToolError('gauge_confidence', error);
207
+ return logToolError(toolName, error);
111
208
  }
112
209
  });
113
- server.tool("plan_and_solve", "Guides internal generation of a **structured plan draft**. Call this tool *with* the generated plan text. Returns the plan text for mandatory `think` analysis to critically evaluate feasibility, refine, and confirm the first action step.", {
114
- generated_plan_text: z.string().describe("The **full, structured plan draft** you generated internally, including goals, steps, potential external tool needs, and risks."),
210
+ /**
211
+ * Tool: plan_and_solve
212
+ * Purpose: Guides the *internal generation* of a structured plan draft.
213
+ * Workflow: Internally generate plan -> Call this tool *with* the plan text -> MANDATORY `think` step follows to analyze/refine the plan.
214
+ * Output: Returns the provided plan text for grounding and analysis.
215
+ */
216
+ server.tool("plan_and_solve", "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*.", {
217
+ generated_plan_text: z.string().describe("The **full, structured plan draft** you generated internally, including goals, steps, potential external tool needs, assumptions, and risks."),
115
218
  task_objective: z.string().describe("The original high-level task objective this plan addresses.")
116
219
  }, async ({ generated_plan_text, task_objective }) => {
117
- logToolCall('plan_and_solve', `Objective: ${task_objective.substring(0, 50)}...`);
220
+ const toolName = 'plan_and_solve';
221
+ logToolCall(toolName, `Objective: ${task_objective.substring(0, 80)}...`);
118
222
  try {
119
223
  if (!generated_plan_text || typeof generated_plan_text !== 'string' || generated_plan_text.trim().length === 0) {
120
- throw new Error('Invalid generated_plan_text: Must be non-empty.');
224
+ throw new Error('Invalid generated_plan_text: Must be a non-empty string containing the plan.');
121
225
  }
122
226
  if (!task_objective || typeof task_objective !== 'string' || task_objective.trim().length === 0) {
123
- throw new Error('Invalid task_objective.');
227
+ throw new Error('Invalid task_objective: Must provide the original objective.');
124
228
  }
125
- logToolResult('plan_and_solve', true, `Returned plan draft (length: ${generated_plan_text.length})`);
126
- // Returns the actual plan text received for analysis.
229
+ logToolResult(toolName, true, `Returned plan draft for analysis (length: ${generated_plan_text.length})`);
230
+ // Returns the actual plan text received. The AI must analyze this in the next 'think' step.
127
231
  return { content: [{ type: "text", text: generated_plan_text }] };
128
232
  }
129
233
  catch (error) {
130
- return logToolError('plan_and_solve', error);
234
+ return logToolError(toolName, error);
131
235
  }
132
236
  });
133
- server.tool("chain_of_thought", "Guides internal generation of **detailed, step-by-step reasoning draft (CoT)**. Call this tool *with* the generated CoT text. Returns the CoT text for mandatory `think` analysis to extract insights, identify flaws/gaps, and plan the next concrete action.", {
134
- generated_cot_text: z.string().describe("The **full, step-by-step Chain of Thought draft** you generated internally."),
135
- problem_statement: z.string().describe("The original problem statement this CoT addresses.")
237
+ /**
238
+ * Tool: chain_of_thought
239
+ * Purpose: Guides the *internal generation* of a detailed, step-by-step reasoning draft (CoT).
240
+ * Workflow: Internally generate CoT -> Call this tool *with* the CoT text -> MANDATORY `think` step follows to analyze the reasoning.
241
+ * Output: Returns the provided CoT text for grounding and analysis.
242
+ */
243
+ server.tool("chain_of_thought", "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.", {
244
+ generated_cot_text: z.string().describe("The **full, step-by-step Chain of Thought draft** you generated internally to solve or analyze the problem."),
245
+ problem_statement: z.string().describe("The original problem statement or question this CoT addresses.")
136
246
  }, async ({ generated_cot_text, problem_statement }) => {
137
- logToolCall('chain_of_thought', `Problem: ${problem_statement.substring(0, 50)}...`);
247
+ const toolName = 'chain_of_thought';
248
+ logToolCall(toolName, `Problem: ${problem_statement.substring(0, 80)}...`);
138
249
  try {
139
250
  if (!generated_cot_text || typeof generated_cot_text !== 'string' || generated_cot_text.trim().length === 0) {
140
- throw new Error('Invalid generated_cot_text: Must be non-empty.');
251
+ throw new Error('Invalid generated_cot_text: Must be a non-empty string containing the CoT.');
141
252
  }
142
253
  if (!problem_statement || typeof problem_statement !== 'string' || problem_statement.trim().length === 0) {
143
- throw new Error('Invalid problem_statement.');
254
+ throw new Error('Invalid problem_statement: Must provide the original problem.');
144
255
  }
145
- logToolResult('chain_of_thought', true, `Returned CoT draft (length: ${generated_cot_text.length})`);
146
- // Returns the actual CoT text received for analysis.
256
+ logToolResult(toolName, true, `Returned CoT draft for analysis (length: ${generated_cot_text.length})`);
257
+ // Returns the actual CoT text received. The AI must analyze this in the next 'think' step.
147
258
  return { content: [{ type: "text", text: generated_cot_text }] };
148
259
  }
149
260
  catch (error) {
150
- return logToolError('chain_of_thought', error);
261
+ return logToolError(toolName, error);
151
262
  }
152
263
  });
153
- server.tool("chain_of_draft", "Signals that one or more **internal drafts** (code, text, plan fragments) have been generated or refined and are ready for analysis. Call this tool *after* generating/refining draft(s) internally. Response confirms readiness; drafts MUST be analyzed via mandatory `think`.", {
154
- draft_description: z.string().describe("Brief description of the draft(s) generated/refined internally (e.g., 'Initial code snippet for function X', 'Refined plan section 3').")
264
+ /**
265
+ * Tool: chain_of_draft
266
+ * Purpose: Signals that internal drafts (code, text, plan fragments) have been generated or refined.
267
+ * Workflow: Internally generate/refine draft(s) -> Call this tool -> MANDATORY `think` step follows to analyze the draft(s).
268
+ * Output: Confirms readiness for analysis.
269
+ */
270
+ server.tool("chain_of_draft", "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.", {
271
+ 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').")
155
272
  }, async ({ draft_description }) => {
156
- logToolCall('chain_of_draft', `Description: ${draft_description}`);
273
+ const toolName = 'chain_of_draft';
274
+ logToolCall(toolName, `Description: ${draft_description}`);
157
275
  try {
158
276
  if (!draft_description || typeof draft_description !== 'string' || draft_description.trim().length === 0) {
159
- throw new Error('Invalid draft_description.');
277
+ throw new Error('Invalid draft_description: Must provide a description.');
160
278
  }
161
- const resultText = `Internal draft(s) ready for analysis: ${draft_description}. MANDATORY: Analyze these draft(s) now in your next 'think' step.`;
162
- logToolResult('chain_of_draft', true);
279
+ 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.`;
280
+ logToolResult(toolName, true);
163
281
  return { content: [{ type: "text", text: resultText }] };
164
282
  }
165
283
  catch (error) {
166
- return logToolError('chain_of_draft', error);
284
+ return logToolError(toolName, error);
167
285
  }
168
286
  });
169
- server.tool("reflection", "Guides internal critical self-evaluation on a prior step, draft, or outcome. Call this tool *with* the **generated critique text**. Returns the critique text for mandatory `think` analysis to plan specific corrective actions or refinements.", {
170
- generated_critique_text: z.string().describe("The **full critique text** you generated internally, identifying flaws, strengths, and suggesting improvements."),
171
- input_subject_description: z.string().describe("A brief description of the original reasoning, plan, code draft, or action result that was critiqued.")
287
+ /**
288
+ * Tool: reflection
289
+ * Purpose: Guides the *internal generation* of a critical self-evaluation (critique) of a prior step, draft, or outcome.
290
+ * Workflow: Internally generate critique -> Call this tool *with* the critique text -> MANDATORY `think` step follows to act on the critique.
291
+ * Output: Returns the provided critique text for grounding and analysis.
292
+ */
293
+ server.tool("reflection", "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.", {
294
+ 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."),
295
+ 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').")
172
296
  }, async ({ generated_critique_text, input_subject_description }) => {
173
- logToolCall('reflection', `Subject: ${input_subject_description}`);
297
+ const toolName = 'reflection';
298
+ logToolCall(toolName, `Subject: ${input_subject_description}`);
174
299
  try {
175
300
  if (!generated_critique_text || typeof generated_critique_text !== 'string' || generated_critique_text.trim().length === 0) {
176
- throw new Error('Invalid generated_critique_text: Must be non-empty.');
301
+ throw new Error('Invalid generated_critique_text: Must be a non-empty string containing the critique.');
177
302
  }
178
303
  if (!input_subject_description || typeof input_subject_description !== 'string' || input_subject_description.trim().length === 0) {
179
- throw new Error('Invalid input_subject_description.');
304
+ throw new Error('Invalid input_subject_description: Must describe what was critiqued.');
180
305
  }
181
- logToolResult('reflection', true, `Returned critique (length: ${generated_critique_text.length})`);
182
- // Returns the actual critique text received for analysis.
306
+ logToolResult(toolName, true, `Returned critique for analysis (length: ${generated_critique_text.length})`);
307
+ // Returns the actual critique text received. The AI must analyze this in the next 'think' step.
183
308
  return { content: [{ type: "text", text: generated_critique_text }] };
184
309
  }
185
310
  catch (error) {
186
- return logToolError('reflection', error);
311
+ return logToolError(toolName, error);
187
312
  }
188
313
  });
189
- server.tool("synthesize_prior_reasoning", "Context Management Tool. Guides internal generation of a **structured summary** of preceding steps, decisions, or context. Call this tool *with* the generated summary text. Returns the summary for mandatory `think` analysis to consolidate understanding and inform next steps.", {
190
- generated_summary_text: z.string().describe("The **full, structured summary text** you generated internally (e.g., key decisions, open questions, current state)."),
191
- context_to_summarize_description: z.string().describe("Description of the reasoning span or context that was summarized.")
314
+ /**
315
+ * Tool: synthesize_prior_reasoning
316
+ * Purpose: Context Management Tool. Guides the *internal generation* of a structured summary of preceding context.
317
+ * Workflow: Internally generate summary -> Call this tool *with* the summary text -> MANDATORY `think` step follows to use the summary.
318
+ * Output: Returns the provided summary text for grounding and analysis.
319
+ */
320
+ server.tool("synthesize_prior_reasoning", "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.", {
321
+ 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)."),
322
+ 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').")
192
323
  }, async ({ generated_summary_text, context_to_summarize_description }) => {
193
- logToolCall('synthesize_prior_reasoning', `Context: ${context_to_summarize_description}`);
324
+ const toolName = 'synthesize_prior_reasoning';
325
+ logToolCall(toolName, `Context: ${context_to_summarize_description}`);
194
326
  try {
195
327
  if (!generated_summary_text || typeof generated_summary_text !== 'string' || generated_summary_text.trim().length === 0) {
196
- throw new Error('Invalid generated_summary_text: Must be non-empty.');
328
+ throw new Error('Invalid generated_summary_text: Must be a non-empty string containing the summary.');
197
329
  }
198
330
  if (!context_to_summarize_description || typeof context_to_summarize_description !== 'string' || context_to_summarize_description.trim().length === 0) {
199
- throw new Error('Invalid context_to_summarize_description.');
331
+ throw new Error('Invalid context_to_summarize_description: Must describe what was summarized.');
200
332
  }
201
- logToolResult('synthesize_prior_reasoning', true, `Returned summary (length: ${generated_summary_text.length})`);
202
- // Returns the actual summary text received for analysis.
333
+ logToolResult(toolName, true, `Returned summary for analysis (length: ${generated_summary_text.length})`);
334
+ // Returns the actual summary text received. The AI must analyze/use this in the next 'think' step.
203
335
  return { content: [{ type: "text", text: generated_summary_text }] };
204
336
  }
205
337
  catch (error) {
206
- return logToolError('synthesize_prior_reasoning', error);
338
+ return logToolError(toolName, error);
207
339
  }
208
340
  });
209
341
  // --- Server Lifecycle and Error Handling ---
210
- process.on('SIGINT', async () => {
211
- console.error('\n[MCP Server] Received SIGINT, shutting down gracefully.');
212
- await server.close();
213
- process.exit(0);
214
- });
215
- process.on('SIGTERM', async () => {
216
- console.error('\n[MCP Server] Received SIGTERM, shutting down gracefully.');
217
- await server.close();
218
- process.exit(0);
219
- });
220
- process.on('uncaughtException', (error, origin) => {
221
- console.error(`[MCP Server] FATAL: Uncaught Exception at: ${origin}`, error);
222
- server.close().catch(err => console.error('[MCP Server] Error during shutdown on uncaughtException:', err)).finally(() => {
342
+ /**
343
+ * Gracefully shuts down the server.
344
+ */
345
+ async function shutdown() {
346
+ console.error('\n[MCP Server] Shutting down gracefully...');
347
+ try {
348
+ await server.close();
349
+ console.error('[MCP Server] Server closed.');
350
+ process.exit(0);
351
+ }
352
+ catch (err) {
353
+ console.error('[MCP Server] Error during shutdown:', err);
223
354
  process.exit(1);
224
- });
355
+ }
356
+ }
357
+ process.on('SIGINT', shutdown);
358
+ process.on('SIGTERM', shutdown);
359
+ process.on('uncaughtException', (error, origin) => {
360
+ const timestamp = new Date().toISOString();
361
+ console.error(`[${timestamp}] [MCP Server] FATAL: Uncaught Exception at: ${origin}`, error);
362
+ // Attempt graceful shutdown, but exit quickly if it fails
363
+ shutdown().catch(() => process.exit(1));
225
364
  });
226
365
  process.on('unhandledRejection', (reason, promise) => {
227
- console.error('[MCP Server] FATAL: Unhandled Promise Rejection:', reason);
228
- server.close().catch(err => console.error('[MCP Server] Error during shutdown on unhandledRejection:', err)).finally(() => {
229
- process.exit(1);
230
- });
366
+ const timestamp = new Date().toISOString();
367
+ console.error(`[${timestamp}] [MCP Server] FATAL: Unhandled Promise Rejection:`, reason);
368
+ // Attempt graceful shutdown, but exit quickly if it fails
369
+ shutdown().catch(() => process.exit(1));
231
370
  });
232
371
  // --- Start the Server ---
372
+ /**
373
+ * Initializes and starts the MCP server.
374
+ */
233
375
  async function main() {
234
376
  try {
235
377
  const transport = new StdioServerTransport();
236
378
  await server.connect(transport);
237
- console.error('-----------------------------------------------------');
238
- console.error(' ᑭᑫᓐᑖᓱᐎᓐ ᐋᐸᒋᒋᑲᓇᓐ - Core Cognitive Tools MCP Server');
239
- console.error(' Status: Running on stdio');
240
- console.error('-----------------------------------------------------');
379
+ const border = '-----------------------------------------------------';
380
+ console.error(border);
381
+ console.error(` ᑭᑫᓐᑖᓱᐎᓐ ᐋᐸᒋᒋᑲᓇᓐ - Core Cognitive Tools Suite v0.9.4: Enables structured, iterative reasoning (Chain of Thought/Draft), planning, and analysis for AI agents, focusing on the cognitive loop. MANDATORY \`think\` step integrates results.`);
382
+ console.error(` Version: ${version}`);
383
+ console.error(' Status: Running on stdio, awaiting MCP requests...');
384
+ console.error(border);
241
385
  }
242
386
  catch (error) {
243
- console.error('[MCP Server] Fatal error during startup:', error);
387
+ const timestamp = new Date().toISOString();
388
+ console.error(`[${timestamp}] [MCP Server] Fatal error during startup:`, error);
244
389
  process.exit(1);
245
390
  }
246
391
  }