### Install Prerequisites (Windows) Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Installs uv, Git, and SQLite using winget on Windows. Alternatively, download directly from their respective websites. ```powershell # Using winget winget install --id=astral-sh.uv -e winget install git.git sqlite.sqlite # Or download directly: # uv: https://docs.astral.sh/uv/ # Git: https://git-scm.com # SQLite: https://www.sqlite.org/download.html ``` -------------------------------- ### Install Prerequisites (macOS) Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Installs uv, Git, and SQLite using Homebrew on macOS. Alternatively, download directly from their respective websites. ```bash # Using Homebrew brew install uv git sqlite3 # Or download directly: # uv: https://docs.astral.sh/uv/ # Git: https://git-scm.com # SQLite: https://www.sqlite.org/download.html ``` -------------------------------- ### Install and Run Pytest Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt These bash commands demonstrate how to install pytest as a development dependency using 'uv' and then execute the tests. ```bash uv add --dev pytest uv run pytest ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Install axios for making HTTP requests and dotenv for managing environment variables. ```bash npm install --save axios dotenv ``` -------------------------------- ### Start Streamable HTTP Server for MCP Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Initialize the DeepSeek MCP Server and start a Streamable HTTP server. This setup is for remote access and requires configuring the DeepSeek API client, conversation store, and server options like host, port, and path. Includes graceful shutdown handling. ```typescript import { createDeepSeekMcpServer } from "./src/mcp-server.js"; import { startStreamableHttpServer } from "./src/transports/http.js"; import { DeepSeekApiClient } from "./src/deepseek/client.js"; import { ConversationStore } from "./src/conversation-store.js"; const client = new DeepSeekApiClient({ apiKey: "sk-..." }); const conversations = new ConversationStore(200); const mcpServer = createDeepSeekMcpServer({ client, conversations, defaultModel: "deepseek-v4-flash", }); const runtime = await startStreamableHttpServer(mcpServer, { host: "0.0.0.0", port: 3001, path: "/mcp", statefulSession: false, // true → server assigns Mcp-Session-Id headers }); console.log("Listening on http://0.0.0.0:3001/mcp"); // Graceful shutdown process.on("SIGTERM", async () => { await runtime.close(); await mcpServer.close(); }); ``` -------------------------------- ### Implement Basic Tool in Python Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of setting up a server and defining/handling tools for calculating the sum of two numbers. ```python app = Server("example-server") @app.list_tools() async def list_tools() -> list[types.Tool]: return [ types.Tool( name="calculate_sum", description="Add two numbers together", inputSchema={ "type": "object", "properties": { "a": {"type": "number"}, "b": {"type": "number"} }, "required": ["a", "b"] } ) ] @app.call_tool() async def call_tool( name: str, arguments: dict ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: if name == "calculate_sum": a = arguments["a"] b = arguments["b"] result = a + b return [types.TextContent(type="text", text=str(result))] raise ValueError(f"Tool not found: {name}") ``` -------------------------------- ### Implement Resource Support in Python Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of setting up a server to list and read resources using decorators. Requires importing types and stdio_server. ```python app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="file:///logs/app.log", name="Application Logs", mimeType="text/plain" ) ] @app.read_resource() async def read_resource(uri: AnyUrl) -> str: if str(uri) == "file:///logs/app.log": log_contents = await read_log_file() return log_contents raise ValueError("Resource not found") # Start server async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` -------------------------------- ### Python Tool Implementation Example Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of how to implement tools in an MCP server using Python, including defining tools and handling tool execution requests. ```APIDOC ## Python Tool Implementation ### Description This example demonstrates how to set up an MCP server in Python to expose and handle tool calls. ### Code Example ```python app = Server("example-server") @app.list_tools() async def list_tools() -> list[types.Tool]: return [ types.Tool( name="calculate_sum", description="Add two numbers together", inputSchema={ "type": "object", "properties": { "a": {"type": "number"}, "b": {"type": "number"} }, "required": ["a", "b"] } ) ] @app.call_tool() async def call_tool( name: str, arguments: dict ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: if name == "calculate_sum": a = arguments["a"] b = arguments["b"] result = a + b return [types.TextContent(type="text", text=str(result))] raise ValueError(f"Tool not found: {name}") ``` ``` -------------------------------- ### Install and Run Inspector Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Run the Inspector directly through npx without installation. Use this for basic testing and debugging. ```bash npx @modelcontextprotocol/inspector ``` ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Implement Resource Support in TypeScript Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of setting up a server to list and read resources. Requires defining request handlers for ListResourcesRequestSchema and ReadResourceRequestSchema. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // List available resources server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "file:///logs/app.log", name: "Application Logs", mimeType: "text/plain" } ] }; }); // Read resource contents server.setRequestHandler(ReadResourceRequestSchema, async (request) => { const uri = request.params.uri; if (uri === "file:///logs/app.log") { const logContents = await readLogFile(); return { contents: [ { uri, mimeType: "text/plain", text: logContents } ] }; } throw new Error("Resource not found"); }); ``` -------------------------------- ### Install uv via Homebrew Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Install the uv package manager using Homebrew. Ensure you have version 0.4.18 or higher. ```bash brew install uv uv --version # Should be 0.4.18 or higher ``` -------------------------------- ### Implement Basic Tool in TypeScript Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of setting up a server and defining/handling tools for calculating the sum of two numbers. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } }); // Define available tools server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "Add two numbers together", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] } }] }; }); // Handle tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "calculate_sum") { const { a, b } = request.params.arguments; return { toolResult: a + b }; } throw new Error("Tool not found"); }); ``` -------------------------------- ### TypeScript Tool Implementation Example Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of how to implement tools in an MCP server using TypeScript, including defining tools and handling tool execution requests. ```APIDOC ## TypeScript Tool Implementation ### Description This example demonstrates how to set up an MCP server in TypeScript to expose and handle tool calls. ### Code Example ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } }); // Define available tools server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "Add two numbers together", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] } }] }; }); // Handle tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "calculate_sum") { const { a, b } = request.params.arguments; return { toolResult: a + b }; } throw new Error("Tool not found"); }); ``` ``` -------------------------------- ### Basic Database Query Example Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of a natural language query to retrieve the average price of all products from the database. ```text What's the average price of all products in the database? ``` -------------------------------- ### Inspect NPM Server Package Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Start server packages from NPM using the Inspector. Ensure the package name and arguments are correct. ```bash npx -y @modelcontextprotocol/inspector npx # For example npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb ``` -------------------------------- ### Example User Prompts for Weather Data Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt These are example prompts you can use to ask Claude about weather information. Claude will use the configured MCP server to retrieve and analyze the data. ```text What's the current weather in San Francisco? Can you analyze the conditions? ``` ```text Can you get me a 5-day forecast for Tokyo and tell me if I should pack an umbrella? ``` ```text Can you analyze the forecast for both Tokyo and San Francisco and tell me which city will be warmer this week? ``` -------------------------------- ### Inspect PyPi Server Package Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Start server packages from PyPi using the Inspector. This command uses 'uvx' to manage Python package execution. ```bash npx @modelcontextprotocol/inspector uvx # For example npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git ``` -------------------------------- ### Example LLM Sampling Request Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt An example demonstrating how a client can request sampling from the LLM, including message content, system prompt, context inclusion, and token limits. ```json { "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What files are in the current directory?" } } ], "systemPrompt": "You are a helpful file system assistant.", "includeContext": "thisServer", "maxTokens": 100 } } ``` -------------------------------- ### Add Base Imports and Setup for Weather Server Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Initializes the Python environment with necessary libraries, configures logging, and sets up API credentials and base URLs for the weather service. ```python import os import json import logging from datetime import datetime, timedelta from collections.abc import Sequence from functools import lru_cache from typing import Any import httpx import asyncio from dotenv import load_dotenv from mcp.server import Server from mcp.types import ( Resource, Tool, TextContent, ImageContent, EmbeddedResource, LoggingLevel ) from pydantic import AnyUrl # Load environment variables load_dotenv() # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("weather-server") # API configuration API_KEY = os.getenv("OPENWEATHER_API_KEY") if not API_KEY: raise ValueError("OPENWEATHER_API_KEY environment variable required") API_BASE_URL = "http://api.openweathermap.org/data/2.5" DEFAULT_CITY = "London" CURRENT_WEATHER_ENDPOINT = "weather" FORECAST_ENDPOINT = "forecast" # The rest of our server implementation will go here ``` -------------------------------- ### Example Sampling Request Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Provides a concrete example of a sampling request, demonstrating how to structure the request with messages, system prompt, context inclusion, and token limits. ```APIDOC ## Example Request Here's an example of requesting sampling from a client: ```json { "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What files are in the current directory?" } } ], "systemPrompt": "You are a helpful file system assistant.", "includeContext": "thisServer", "maxTokens": 100 } } ``` ``` -------------------------------- ### Data Analysis Query Example Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of a natural language query for analyzing price distribution and suggesting optimizations. ```text Can you analyze the price distribution and suggest any pricing optimizations? ``` -------------------------------- ### Complex Database Operation Example Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Example of a natural language query to design and create a new table for storing customer orders. ```text Could you help me design and create a new table for storing customer orders? ``` -------------------------------- ### Troubleshoot Installation Issues Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt These bash commands help diagnose and resolve installation problems. They include checking the Python version and reinstalling project dependencies using 'uv sync --reinstall'. ```bash # Check Python version python --version # Reinstall dependencies uv sync --reinstall ``` -------------------------------- ### Install Additional Python Dependencies Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Add httpx and python-dotenv to your project's dependencies using uv. ```bash uv add httpx python-dotenv ``` -------------------------------- ### Prompt Claude Desktop to Query SQLite Database Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt This is an example prompt to send to Claude Desktop after configuring the SQLite MCP server. It asks Claude to connect to the database, list available products, and their prices. ```text Can you connect to my SQLite database and tell me what products are available, and their prices? ``` -------------------------------- ### Implement MCP Server Prompts in Python Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt This Python example shows how to implement an MCP server for handling prompts. It defines 'git-commit' and 'explain-code' prompts and uses decorators to register handlers for listing and retrieving prompts. ```python from mcp.server import Server import mcp.types as types # Define available prompts PROMPTS = { "git-commit": types.Prompt( name="git-commit", description="Generate a Git commit message", arguments=[ types.PromptArgument( name="changes", description="Git diff or description of changes", required=True ) ], ), "explain-code": types.Prompt( name="explain-code", description="Explain how code works", arguments=[ types.PromptArgument( name="code", description="Code to explain", required=True ), types.PromptArgument( name="language", description="Programming language", required=False ) ], ) } # Initialize server app = Server("example-prompts-server") @app.list_prompts() async def list_prompts() -> list[types.Prompt]: return list(PROMPTS.values()) @app.get_prompt() async def get_prompt( name: str, arguments: dict[str, str] | None = None ) -> types.GetPromptResult: if name not in PROMPTS: raise ValueError(f"Prompt not found: {name}") if name == "git-commit": changes = arguments.get("changes") if arguments else "" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", text=f"Generate a concise but descriptive commit message " f"for these changes:\n\n{changes}" ) ) ] ) if name == "explain-code": code = arguments.get("code") if arguments else "" language = arguments.get("language", "Unknown") if arguments else "Unknown" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", ``` -------------------------------- ### Build and Run DeepSeek MCP Server from Source Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Compile the server from source code. This requires Node.js version 20 or higher. Install dependencies, build the project, and then run the server. ```bash npm install npm run build DEEPSEEK_API_KEY="sk-..." node build/index.js ``` -------------------------------- ### Implement MCP Server in Python Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Basic example of implementing an MCP server in Python using the SDK. Handles resource listing requests and connects via stdio transport. ```python import asyncio import mcp.types as types from mcp.server import Server from mcp.server.stdio import stdio_server app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="example://resource", name="Example Resource" ) ] async def main(): async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) if __name__ == "__main__": asyncio.run(main) ``` -------------------------------- ### Check Python Version Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Verify that Python 3.10 or higher is installed on your system. ```bash python --version # Should be 3.10 or higher ``` -------------------------------- ### Check Node.js Version Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Verify that Node.js version 18 or higher is installed. This is a prerequisite for the project. ```bash node --version # Should be v18 or higher npm --version ``` -------------------------------- ### Setup Tool Handlers Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt This TypeScript code sets up request handlers for listing available tools and calling specific tools, such as 'get_forecast'. It includes input validation and API calls for forecast data. ```typescript private setupToolHandlers(): void { this.server.setRequestHandler( ListToolsRequestSchema, async () => ({ tools: [{ name: "get_forecast", description: "Get weather forecast for a city", inputSchema: { type: "object", properties: { city: { type: "string", description: "City name" }, days: { type: "number", description: "Number of days (1-5)", minimum: 1, maximum: 5 } }, required: ["city"] } }] }) ); this.server.setRequestHandler( CallToolRequestSchema, async (request) => { if (request.params.name !== "get_forecast") { throw new McpError( ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}` ); } if (!isValidForecastArgs(request.params.arguments)) { throw new McpError( ErrorCode.InvalidParams, "Invalid forecast arguments" ); } const city = request.params.arguments.city; const days = Math.min(request.params.arguments.days || 3, 5); try { const response = await this.axiosInstance.get<{ list: OpenWeatherResponse[] }>(API_CONFIG.ENDPOINTS.FORECAST, { params: { q: city, cnt: days * 8 // API returns 3-hour intervals } }); const forecasts: ForecastDay[] = []; for (let i = 0; i < response.data.list.length; i += 8) { const dayData = response.data.list[i]; forecasts.push({ date: dayData.dt_txt?.split(' ')[0] ?? new Date().toISOString().split('T')[0], temperature: dayData.main.temp, conditions: dayData.weather[0].description }); } return { content: [{ type: "text", text: JSON.stringify(forecasts, null, 2) }] }; } catch (error) { if (axios.isAxiosError(error)) { return { content: [{ type: "text", text: `Weather API error: ${error.response?.data.message ?? error.message}` }], isError: true, } } throw error; } } ); } ``` ``` -------------------------------- ### Implement MCP Server Prompts in TypeScript Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt This TypeScript example demonstrates how to set up an MCP server to handle prompt requests. It defines two prompts: 'git-commit' and 'explain-code', and registers request handlers for listing prompts and retrieving specific prompt details. ```typescript import { Server } from "@modelcontextprotocol/sdk/server"; import { ListPromptsRequestSchema, GetPromptRequestSchema } from "@modelcontextprotocol/sdk/types"; const PROMPTS = { "git-commit": { name: "git-commit", description: "Generate a Git commit message", arguments: [ { name: "changes", description: "Git diff or description of changes", required: true } ] }, "explain-code": { name: "explain-code", description: "Explain how code works", arguments: [ { name: "code", description: "Code to explain", required: true }, { name: "language", description: "Programming language", required: false } ] } }; const server = new Server({ name: "example-prompts-server", version: "1.0.0" }, { capabilities: { prompts: {} } }); // List available prompts server.setRequestHandler(ListPromptsRequestSchema, async () => { return { prompts: Object.values(PROMPTS) }; }); // Get specific prompt server.setRequestHandler(GetPromptRequestSchema, async (request) => { const prompt = PROMPTS[request.params.name]; if (!prompt) { throw new Error(`Prompt not found: ${request.params.name}`); } if (request.params.name === "git-commit") { return { messages: [ { role: "user", content: { type: "text", text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}` } } ] }; } if (request.params.name === "explain-code") { const language = request.params.arguments?.language || "Unknown"; return { messages: [ { role: "user", content: { type: "text", text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}` } } ] }; } throw new Error("Prompt implementation not found"); }); ``` -------------------------------- ### Configure and Run Type Checker Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt These bash commands show how to install the 'pyright' type checker as a development dependency and then run it against the 'src' directory to check for type errors. ```bash # Install mypy uv add --dev pyright # Run type checker uv run pyright src ``` -------------------------------- ### Run DeepSeek MCP Server Locally with Stdio Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/README.md Start the DeepSeek MCP server locally using Node.js and stdio transport. Requires the DEEPSEEK_API_KEY environment variable. ```bash DEEPSEEK_API_KEY="REPLACE_WITH_DEEPSEEK_KEY" npx -y deepseek-mcp-server ``` -------------------------------- ### Multi-step Debug Workflow Example Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Demonstrates a dynamic prompt defined as a JavaScript object that generates messages for a multi-step debugging workflow based on user input. ```typescript const debugWorkflow = { name: "debug-error", async getMessages(error: string) { return [ { role: "user", content: { type: "text", text: `Here's an error I'm seeing: ${error}` } }, { role: "assistant", content: { type: "text", text: "I'll help analyze this error. What have you tried so far?" } }, { role: "user", content: { type: "text", text: "I've tried restarting the service, but the error persists." } } ]; } }; ``` -------------------------------- ### Implement MCP Server in TypeScript Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Basic example of implementing an MCP server in TypeScript using the SDK. Handles resource listing requests and connects via stdio transport. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // Handle requests server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "example://resource", name: "Example Resource" } ] }; }); // Connect transport const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Get Prompt Request and Response Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Shows how to request a specific prompt by name and arguments, and the structure of the response containing messages for the LLM. ```typescript // Request { method: "prompts/get", params: { name: "analyze-code", arguments: { language: "python" } } } ``` ```typescript // Response { description: "Analyze Python code for potential improvements", messages: [ { role: "user", content: { type: "text", text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```" } } ] } ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Create a .env file to store your OpenWeatherMap API key. ```bash OPENWEATHER_API_KEY=your-api-key-here ``` -------------------------------- ### Set up Environment Variables Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Create a .env file to store your OpenWeatherMap API key. Ensure this file is added to .gitignore to prevent accidental commits. ```bash OPENWEATHER_API_KEY=your-api-key-here ``` ```bash .env ``` -------------------------------- ### Package Entry Point Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Sets up the main entry point for the Python package using asyncio.run to execute the server's main function. It also exposes important items like 'main' and 'server' at the package level. ```python from . import server import asyncio def main(): """Main entry point for the package.""" asyncio.run(server.main()) # Optionally expose other important items at package level __all__ = ['main', 'server'] ``` -------------------------------- ### Create New TypeScript Server Project Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Bootstrap a new project using the create-typescript-server tool. Navigate into the created directory. ```bash npx @modelcontextprotocol/create-server weather-server cd weather-server ``` -------------------------------- ### DeepSeekApiClient Initialization Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Demonstrates how to initialize the DeepSeekApiClient with an API key and optional base URL and timeout. ```APIDOC ## DeepSeekApiClient Initialization ### Description Initialize the `DeepSeekApiClient` with your API key. You can optionally specify a custom `baseUrl` and `timeoutMs`. A custom `fetchFn` can be provided for testing purposes. ### Code Example ```typescript import { DeepSeekApiClient } from "./src/deepseek/client.js"; const client = new DeepSeekApiClient({ apiKey: "sk-...", baseUrl: "https://api.deepseek.com", // default timeoutMs: 30000, // fetchFn: myMockFetch, // override for unit tests }); ``` ``` -------------------------------- ### Get User Balance with MCP Tool Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Calls the GET /user/balance endpoint to retrieve account availability and balance breakdown. Use `is_available` to guard against expensive calls. ```typescript const result = await mcpClient.callTool({ name: "get_user_balance", arguments: {}, }); console.log(result.content[0].text); // { // "is_available": true, // "balance_infos": [ // { // "currency": "USD", // "total_balance": "8.42", // "granted_balance": "0.00", // "topped_up_balance": "8.42" // } // ] // } // Use is_available to guard before expensive calls: if (!result.structuredContent.is_available) { throw new Error("DeepSeek account is not available — check billing."); } ``` -------------------------------- ### Create SQLite Database on macOS Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Use this bash script to create a sample SQLite database named 'test.db' with a 'products' table and populate it with initial data. This is the first step in setting up the database for Claude Desktop integration. ```bash # Create a new SQLite database sqlite3 ~/test.db < ReadResourceResult: # ... ``` -------------------------------- ### Configure and Use Logging Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Sets up a logger for the weather server and provides a method to dynamically set the logging level. It also demonstrates how to send log messages to the client session. ```python # Set up logging logger = logging.getLogger("weather-server") logger.setLevel(logging.INFO) @app.set_logging_level() async def set_logging_level(level: LoggingLevel) -> EmptyResult: logger.setLevel(level.upper()) await app.request_context.session.send_log_message( level="info", data=f"Log level set to {level}", logger="weather-server" ) return EmptyResult() # Use logger throughout the code # For example: # logger.info("Weather data fetched successfully") # logger.error(f"Error fetching weather data: {str(e)}") ``` -------------------------------- ### Get User Balance Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Retrieves the current user's account balance information. ```APIDOC ## Get User Balance ### Description Retrieves information about the user's current account balance, including availability and breakdown. ### Method `client.getUserBalance()` ### Response - **is_available** (boolean) - Indicates if the balance information is available. - **balance_infos** (array) - An array of balance information objects. - **currency** (string) - The currency of the balance (e.g., `"USD"`). - **total_balance** (string) - The total balance amount. - **granted_balance** (string) - The granted balance amount. - **topped_up_balance** (string) - The topped-up balance amount. ### Request Example ```typescript const balance = await client.getUserBalance(); console.log(balance.is_available); console.log(balance.balance_infos[0]); ``` ``` -------------------------------- ### Create New MCP Server Project Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Use the create-mcp-server command to scaffold a new project and navigate into the project directory. ```bash uvx create-mcp-server --path weather_service cd weather_service ``` -------------------------------- ### Initialize MCP Server and Configure Axios Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Sets up the base structure for an MCP server, including importing necessary SDK components, configuring Axios for API requests, and defining initial server properties and error handling. Requires OPENWEATHER_API_KEY environment variable. ```typescript #!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js"; import axios from "axios"; import dotenv from "dotenv"; import { WeatherData, ForecastDay, OpenWeatherResponse, isValidForecastArgs } from "./types.js"; dotenv.config(); const API_KEY = process.env.OPENWEATHER_API_KEY; if (!API_KEY) { throw new Error("OPENWEATHER_API_KEY environment variable is required"); } const API_CONFIG = { BASE_URL: 'http://api.openweathermap.org/data/2.5', DEFAULT_CITY: 'San Francisco', ENDPOINTS: { CURRENT: 'weather', FORECAST: 'forecast' } } as const; class WeatherServer { private server: Server; private axiosInstance; constructor() { this.server = new Server({ name: "example-weather-server", version: "0.1.0" }, { capabilities: { resources: {}, tools: {} } }); // Configure axios with defaults this.axiosInstance = axios.create({ baseURL: API_CONFIG.BASE_URL, params: { appid: API_KEY, units: "metric" } }); this.setupHandlers(); this.setupErrorHandling(); } private setupErrorHandling(): void { this.server.onerror = (error) => { console.error("[MCP Error]", error); }; process.on('SIGINT', async () => { await this.server.close(); process.exit(0); }); } private setupHandlers(): void { this.setupResourceHandlers(); this.setupToolHandlers(); } private setupResourceHandlers(): void { // Implementation continues in next section } private setupToolHandlers(): void { // Implementation continues in next section } async run(): Promise { const transport = new StdioServerTransport(); await this.server.connect(transport); // Although this is just an informative message, we must log to stderr, // to avoid interfering with MCP communication that happens on stdout console.error("Weather MCP server running on stdio"); } } const server = new WeatherServer(); server.run().catch(console.error); ``` -------------------------------- ### MCP Server Structure and Handlers Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Illustrates the basic structure of an MCP server using a Python app pattern. It shows how to create a `Server` instance and register handlers for different MCP operations like listing resources, calling tools, and reading resources using decorators. ```python # Create server instance with name app = Server("weather-server") # Register resource handler @app.list_resources() async def list_resources() -> list[Resource]: """List available resources""" return [...] # Register tool handler @app.call_tool() async def call_tool(name: str, arguments: Any) -> Sequence[TextContent]: """Handle tool execution""" return [...] # Register additional handlers @app.read_resource() ... @app.list_tools() ... ``` -------------------------------- ### Get User Account Balance Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Fetch the user's account balance information. Checks if the balance is available and logs the details of the first balance entry. ```typescript // Account balance const balance = await client.getUserBalance(); console.log(balance.is_available); // true console.log(balance.balance_infos[0]); ``` -------------------------------- ### Configure PostgreSQL Connection Server Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt JSON configuration to connect Claude Desktop to a PostgreSQL database. Requires Node.js and npx. ```json "postgres": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"] } ``` -------------------------------- ### Create SQLite Database on Windows Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Use this PowerShell script to create a sample SQLite database named 'test.db' with a 'products' table and populate it with initial data. This is the first step in setting up the database for Claude Desktop integration on Windows. ```powershell # Create a new SQLite database $sql = @' CREATE TABLE products ( id INTEGER PRIMARY KEY, name TEXT, price REAL ); INSERT INTO products (name, price) VALUES ('Widget', 19.99), ('Gadget', 29.99), ('Gizmo', 39.99), ('Smart Watch', 199.99), ('Wireless Earbuds', 89.99), ('Portable Charger', 24.99), ('Bluetooth Speaker', 79.99), ('Phone Stand', 15.99), ('Laptop Sleeve', 34.99), ('Mini Drone', 299.99), ('LED Desk Lamp', 45.99), ('Keyboard', 129.99), ('Mouse Pad', 12.99), ('USB Hub', 49.99), ('Webcam', 69.99), ('Screen Protector', 9.99), ('Travel Adapter', 27.99), ('Gaming Headset', 159.99), ('Fitness Tracker', 119.99), ('Portable SSD', 179.99); '@ cd ~ & sqlite3 test.db $sql ``` -------------------------------- ### Implement Tool Handlers for Weather Forecasts Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Sets up handlers for weather-related tools. `list_tools` advertises the `get_forecast` tool, and `call_tool` processes calls to this tool, fetching forecast data based on city and number of days. ```python app = Server("weather-server") # Resource implementation ... @app.list_tools() async def list_tools() -> list[Tool]: """List available weather tools.""" return [ Tool( name="get_forecast", description="Get weather forecast for a city", inputSchema={ "type": "object", "properties": { "city": { "type": "string", "description": "City name" }, "days": { "type": "number", "description": "Number of days (1-5)", "minimum": 1, "maximum": 5 } }, "required": ["city"] } ) ] @app.call_tool() async def call_tool(name: str, arguments: Any) -> Sequence[TextContent | ImageContent | EmbeddedResource]: """Handle tool calls for weather forecasts.""" if name != "get_forecast": raise ValueError(f"Unknown tool: {name}") if not isinstance(arguments, dict) or "city" not in arguments: raise ValueError("Invalid forecast arguments") city = arguments["city"] days = min(int(arguments.get("days", 3)), 5) try: async with httpx.AsyncClient() as client: response = await client.get( f"{API_BASE_URL}/{FORECAST_ENDPOINT}", ``` -------------------------------- ### Defining a Tool for Weather Forecast Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt This defines a tool that Claude can use to get a weather forecast. It includes the tool's name, a description of its function, and a schema for its input parameters, ensuring type-safe interactions. ```typescript { name: "get_forecast", description: "Get weather forecast for a city", inputSchema: { type: "object", properties: { city: { type: "string" }, days: { type: "number" } } } } ``` -------------------------------- ### Define Transport Interface in TypeScript Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Defines the core interface for custom transports in MCP, outlining methods for starting, sending messages, and closing connections, along with essential callbacks for error and message events. ```typescript interface Transport { // Start processing messages start(): Promise; // Send a JSON-RPC message send(message: JSONRPCMessage): Promise; // Close the connection close(): Promise; // Callbacks onclose?: () => void; onerror?: (error: Error) => void; onmessage?: (message: JSONRPCMessage) => void; } ``` -------------------------------- ### Configure File System Access Server Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt JSON configuration to enable file system access for Claude Desktop. Requires Node.js and npx. ```json "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/YOUR_USERNAME/Desktop"] } ``` -------------------------------- ### MCP List Models Tool Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt The `list_models` tool retrieves all available DeepSeek model IDs by calling `GET /models`. It requires no parameters and returns model information in both plain text and structured JSON formats. ```typescript const result = await mcpClient.callTool({ name: "list_models", arguments: {}, }); console.log(result.content[0].text); // deepseek-v4-flash // deepseek-v4-pro console.log(result.structuredContent); // { // object: "list", // data: [ // { id: "deepseek-v4-flash", object: "model", owned_by: "deepseek" }, // { id: "deepseek-v4-pro", object: "model", owned_by: "deepseek" } // ] // } ``` -------------------------------- ### Build and Test Server Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Standard npm commands to build and test the Deepseek MCP server project. ```bash npm run build ``` -------------------------------- ### Weather Service Integration Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt This code snippet handles fetching and processing weather data from an API. It parses the response to extract daily forecasts including date, temperature, and conditions. Ensure httpx is installed for HTTP requests and logging is configured. ```python params={ "q": city, "cnt": days * 8, # API returns 3-hour intervals **http_params, } ) response.raise_for_status() data = response.json() forecasts = [] for i in range(0, len(data["list"]), 8): day_data = data["list"][i] forecasts.append({ "date": day_data["dt_txt"].split()[0], "temperature": day_data["main"]["temp"], "conditions": day_data["weather"][0]["description"] }) return [ TextContent( type="text", text=json.dumps(forecasts, indent=2) ) ] except httpx.HTTPError as e: logger.error(f"Weather API error: {str(e)}") raise RuntimeError(f"Weather API error: {str(e)}") ``` -------------------------------- ### Defining MCP Tool Schema Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Define a tool that Claude can use to perform actions. This example shows the structure for a `get_forecast` tool, including its name, description, and input schema with properties for city and days, specifying required fields and constraints. ```python Tool( name="get_forecast", description="Get weather forecast for a city", inputSchema={ "type": "object", "properties": { "city": { "type": "string", "description": "City name" }, "days": { "type": "number", "description": "Number of days (1-5)", "minimum": 1, "maximum": 5 } }, "required": ["city"] } ) ``` -------------------------------- ### Implement Resource Handler for Current Weather Source: https://github.com/dmontgomery40/deepseek-mcp-server/blob/main/src/docs/llms-full.txt Adds a request handler for listing resources, specifically defining the 'current weather' resource. Also includes the start of a handler for reading a resource, which fetches current weather data using Axios. ```typescript this.server.setRequestHandler( ListResourcesRequestSchema, async () => ({ resources: [{ uri: `weather://${API_CONFIG.DEFAULT_CITY}/current`, name: `Current weather in ${API_CONFIG.DEFAULT_CITY}`, mimeType: "application/json", description: "Real-time weather data including temperature, conditions, humidity, and wind speed" }] }) ); this.server.setRequestHandler( ReadResourceRequestSchema, async (request) => { const city = API_CONFIG.DEFAULT_CITY; if (request.params.uri !== `weather://${city}/current`) { throw new McpError( ErrorCode.InvalidRequest, `Unknown resource: ${request.params.uri}` ); } try { const response = await this.axiosInstance.get( ``` -------------------------------- ### Initialize DeepSeekApiClient Source: https://context7.com/dmontgomery40/deepseek-mcp-server/llms.txt Instantiate the DeepSeekApiClient with your API key and optional base URL or timeout. A custom fetch function can be provided for testing purposes. ```typescript import { DeepSeekApiClient, DeepSeekApiError } from "./src/deepseek/client.js"; const client = new DeepSeekApiClient({ apiKey: "sk-…", baseUrl: "https://api.deepseek.com", // default timeoutMs: 30000, // fetchFn: myMockFetch, // override for unit tests }); ```