#
tokens: 3026/50000 9/9 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .gitignore
├── bin
│   └── deep-reasoning-mcp.js
├── biome.json
├── LICENSE
├── package.json
├── pnpm-lock.yaml
├── README.md
├── rslib.config.ts
├── src
│   ├── index.ts
│   ├── prompt.ts
│   └── sse.ts
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
# Local
.DS_Store
*.local
*.log*

# Dist
node_modules
dist/

# IDE
.vscode/*
!.vscode/extensions.json
.idea

```

--------------------------------------------------------------------------------
/bin/deep-reasoning-mcp.js:
--------------------------------------------------------------------------------

```javascript
#!/usr/bin/env node

async function main() {
  const { run } = await import("../dist/index.js");

  try {
    run();
  } catch (err) {
    console.error(err);
  }
}

main();

```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "lib": ["ES2021"],
    "module": "ESNext",
    "noEmit": true,
    "strict": true,
    "skipLibCheck": true,
    "isolatedModules": true,
    "resolveJsonModule": true,
    "moduleResolution": "bundler",
    "useDefineForClassFields": true,
    "allowImportingTsExtensions": true
  },
  "include": ["src"]
}

```

--------------------------------------------------------------------------------
/biome.json:
--------------------------------------------------------------------------------

```json
{
  "$schema": "https://biomejs.dev/schemas/1.8.0/schema.json",
  "organizeImports": {
    "enabled": true
  },
  "vcs": {
    "enabled": true,
    "clientKind": "git",
    "useIgnoreFile": true
  },
  "formatter": {
    "indentStyle": "space"
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "single"
    }
  },
  "css": {
    "parser": {
      "cssModules": true
    }
  },
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true
    }
  }
}

```

--------------------------------------------------------------------------------
/rslib.config.ts:
--------------------------------------------------------------------------------

```typescript
import { defineConfig } from "@rslib/core";
import pkg from "./package.json";

export default defineConfig({
  lib: [
    {
      format: "esm",
      syntax: "es2021",
      dts: true,
    },
    {
      format: "cjs",
      syntax: "es2021",
    },
  ],
  source: {
    entry: {
      index: "./src/index.ts",
      sse: "./src/sse.ts",
    },
    define: {
      "process.env.APP_NAME": JSON.stringify(pkg.name),
      "process.env.APP_VERSION": JSON.stringify(pkg.version),
    },
  },
});

```

--------------------------------------------------------------------------------
/src/sse.ts:
--------------------------------------------------------------------------------

```typescript
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import express from "express";
import { server } from "./index.ts";

const app = express();

let transport: SSEServerTransport;

app.get("/sse", async (req, res) => {
  console.log("Received connection");
  transport = new SSEServerTransport("/message", res);
  await server.connect(transport);
});

app.post("/message", async (req, res) => {
  console.log("Received message");
  console.log(req);

  await transport.handlePostMessage(req, res);
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "deep-reasoning-mcp",
  "version": "0.1.1",
  "description": "Deep reasoning MCP Server",
  "author": {
    "name": "Lakphy",
    "email": "[email protected]"
  },
  "license": "MIT",
  "keywords": [
    "mcp",
    "ai",
    "reasoning",
    "model-context-protocol"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/lakphy/deep-reasoning-mcp.git"
  },
  "homepage": "https://github.com/lakphy/deep-reasoning-mcp#readme",
  "bugs": {
    "url": "https://github.com/lakphy/deep-reasoning-mcp/issues"
  },
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  },
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "files": [
    "dist",
    "bin"
  ],
  "bin": {
    "deep-reasoning-mcp": "./bin/deep-reasoning-mcp.js"
  },
  "scripts": {
    "build": "rslib build",
    "dev": "rslib build --watch",
    "start": "nodemon dist/index.js",
    "start:sse": "nodemon dist/sse.js",
    "debug": "npx @modelcontextprotocol/inspector node bin/deep-reasoning-mcp.js",
    "check": "biome check --write",
    "format": "biome format --write"
  },
  "devDependencies": {
    "@biomejs/biome": "^1.9.4",
    "@modelcontextprotocol/inspector": "^0.4.1",
    "@rslib/core": "^0.4.1",
    "@types/node": "^22.13.4",
    "nodemon": "^3.0.2",
    "typescript": "^5.7.3",
    "@types/express": "^5.0.0"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.5.0",
    "@openrouter/ai-sdk-provider": "^0.2.1",
    "ai": "^4.1.40",
    "zod": "^3.24.2",
    "express": "^4.21.2"
  }
}

```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
import { streamText } from "ai";
import {
  getReasoningModelProcessTarget,
  getReasoningModelSystem,
  getResponsePrompt,
} from "./prompt";

const apiKey =
  process.argv.find((arg) => arg.startsWith("--apiKey="))?.split("=")[1] ||
  process.env.OPEN_ROUTER_API_KEY;

const model =
  process.argv.find((arg) => arg.startsWith("--model="))?.split("=")[1] ||
  "deepseek/deepseek-r1-distill-qwen-32b";

if (!apiKey) {
  throw new Error("API key is required");
}

const openrouter = createOpenRouter({
  apiKey: apiKey,
});

export const server = new McpServer({
  name: process.env.APP_NAME || "deep-reasoning-server",
  version: process.env.APP_VERSION || "0.1.0",
});

server.tool(
  "deep-reasoning",
  "Deep inference analysis of any input. This is a powerful deep reasoning tool that helps in analyzing issues, user intent, code logic, etc. This tool should be prioritized for analysis before working on any problem. If you can connect to the internet, you can search for more information as context before reasoning.",
  {
    statement: z
      .string()
      .describe(
        "Content to be analyzed by inference, which can be questions, statements, user intent, etc."
      ),
    context: z
      .string()
      .optional()
      .describe(
        "Important contextual information for enhancing the accuracy and completeness of reasoning. It is highly recommended to provide relevant contextual information, historical data, constraints, etc. for a more comprehensive analysis. Even in cases of uncertainty, it is recommended to provide context that may be relevant"
      ),
  },
  async ({ statement, context }) => {
    try {
      const startTime = Date.now();
      const result = streamText({
        model: openrouter(model, {
          includeReasoning: true,
        }),
        system: getReasoningModelSystem(),
        messages: [
          {
            role: "user",
            content: getReasoningModelProcessTarget({ statement, context }),
          },
        ],
      });

      for await (const textPart of result.textStream) continue;

      const resultText = await result.text;
      const resultReasoning = await result.reasoning;

      const duration = (Date.now() - startTime) / 1000;

      return {
        content: [
          {
            type: "text",
            text: getResponsePrompt({
              text: resultText,
              reasoning: resultReasoning || "",
              duration,
            }),
          },
        ],
      };
    } catch (error) {
      return {
        content: [{ type: "text", text: JSON.stringify({ error }) }],
      };
    }
  }
);

export async function run() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

```

--------------------------------------------------------------------------------
/src/prompt.ts:
--------------------------------------------------------------------------------

```typescript
export const getResponsePrompt = ({
  text,
  reasoning,
  duration,
}: {
  text: string;
  reasoning: string;
  duration: number;
}) => `
<reasoning>

${reasoning ? ["<idea>", reasoning, "</idea>"].join("\n") : ""}

${text ? ["<text>", text, "</text>"].join("\n") : ""}

<rules>

Please analyze the above carefully:
1. the <text> section contains the preliminary conclusions of the reasoning tool
2. the <idea> section (if present) shows the thinking process of the reasoning

Your task is to:
1. understand and synthesize the information in both sections
2. provide an optimized answer to the requirement:
   - More concise: remove redundant information and emphasize core points
   - More accurate: correcting possible errors and ensuring the accuracy of the information
   - More complete: add context or details as necessary.
3. point out and correct any logical gaps in reasoning, if you find them

Please output the final answer in clear, professional language.

</rules>

<others>

Reasoning time: ${duration} seconds
Telling users the reasoning time improves user experience and professionalism.

</others>

<reasoning>
`;

export const getReasoningModelSystem = () => `
<task>

You are a professional reasoning and analysis engine that specializes in in-depth, systematic analysis of all types of problems. Your main responsibility is to perform a thorough inference analysis of any user-provided content (questions, statements, intentions, etc.) to help understand the nature of the problem and draw reasonable conclusions.

</task>

<reasoning_framework>

1. Deep understanding
   - Accurately grasp the core issue and key messages
   - Identify the nature and potential impact of the issue
   - Analyze the background and context of the issue
   - Consider multiple dimensions of the issue

2. Systems analysis
   - Decompose complex problems into manageable sub-problems
   - Establish logical linkages between problems
   - Identify key variables and influences
   - Consider short- and long-term impacts

3. Multidimensional reasoning
   - Logical reasoning: using deductive and inductive methods
   - Causal reasoning: analyzing chains of cause and effect
   - Analogical reasoning: drawing on similar experiences
   - Systematic reasoning: considering wholes and correlations
   - Critical thinking: questioning and testing assumptions

4. Conclusion generation
   - Synthesizing results from multiple perspectives
   - Weighing the pros and cons of different options
   - Provide specific supporting arguments
   - Explain conditions and limitations of the conclusions

5. Output optimization
   - Ensure the accuracy and reliability of the conclusions
   - Maintain clarity and conciseness of presentation
   - Highlight key findings and recommendations
   - Provide actionable insights

</reasoning_framework>

<guidelines>

- Maintains an objective and neutral position at all times
- Utilize a rigorous logical reasoning process
- Considers multiple possible perspectives and scenarios
- Clearly identifies uncertainties and risks
- Provides concrete examples and supporting arguments
- Utilize contextual information
- Ensure that conclusions have real value
- Avoid oversimplifying complex issues

</guidelines>
`;

export const getReasoningModelProcessTarget = ({
  statement,
  context,
}: {
  statement: string;
  context?: string;
}) => `
<input>
${statement}
</input>

${
  context
    ? `<context>
${context}
</context>`
    : ""
}

<rules>

Please analyze the inputs by in-depth and systematic reasoning. This analytical process is critical and will directly affect the quality of subsequent decisions and actions. Please follow the steps outlined below:

1. Comprehensive understanding
   - Carefully analyze all aspects of the problem
   - Identify key messages and core elements
   - Consider the background and context of the issue

2. Systematic reasoning
   - Utilizes a variety of reasoning methods
   - Establish a clear chain of logic
   - Consider multiple possible perspectives
   - Analyze potential impacts and risks

3. Conclusion generation
   - Provide clear and precise conclusions
   - Provide clear and precise conclusions
   - Describe conditions and limitations of applicability
   - Highlight key findings and recommendations

Output Requirements:
1. the reasoning process should be systematic and rigorous
2. conclusions should be accurate, practical and concise
3. clearly identify uncertainties, but do not require questions
4. ensure that the output is practically informative

</rules>
`;

```