DeepSeek MCP Server

DeepSeek MCP Server

Okay, here's a basic outline and code snippet for a simple MCP (presumably meaning something like "Message Control Protocol" or "Message Coordination Proxy" in this context) server in Go that redirects questions to Deepseek models. I'll focus on the core functionality: receiving a request, forwarding it to a Deepseek model (assuming a Deepseek API endpoint), and returning the response. **Important Considerations and Assumptions:** * **Deepseek API:** This code assumes you have access to a Deepseek API endpoint that accepts a question (likely as a JSON payload) and returns a response (also likely as JSON). You'll need to replace the placeholder URL (`"https://api.deepseek.com/v1/completions"`) with the actual Deepseek API endpoint. You'll also need to handle authentication (API keys, etc.) as required by the Deepseek API. * **Error Handling:** The code includes basic error handling, but you'll want to expand it for production use. Consider logging errors, implementing retry mechanisms, and providing more informative error responses to the client. * **JSON Handling:** The code uses JSON for request and response serialization. Adjust the data structures if the Deepseek API uses a different format. * **Concurrency:** The code handles each request in a separate goroutine, allowing the server to handle multiple requests concurrently. * **Dependencies:** You'll need the `net/http` and `encoding/json` packages, which are part of the Go standard library. You might also need a package like `io/ioutil` for reading the response body. * **Security:** This is a *very* basic example. For production, you'll need to consider security aspects like input validation, rate limiting, and authentication/authorization. * **MCP Definition:** I'm assuming "MCP" is a custom term in your context. This code provides a simple proxy/redirector. If MCP has more specific requirements (e.g., message queuing, transformation, routing rules), you'll need to adapt the code accordingly. **Code Example (main.go):** ```go package main import ( "bytes" "encoding/json" "fmt" "io" "log" "net/http" "os" ) // RequestPayload represents the structure of the incoming request. Adjust as needed. type RequestPayload struct { Question string `json:"question"` } // ResponsePayload represents the structure of the response from Deepseek. Adjust as needed. type ResponsePayload struct { Answer string `json:"answer"` } // deepseekAPIEndpoint is a placeholder. Replace with the actual Deepseek API URL. const deepseekAPIEndpoint = "https://api.deepseek.com/v1/completions" // Replace with the actual Deepseek API endpoint // deepseekAPIKey is a placeholder. Replace with your actual Deepseek API key. const deepseekAPIKey = "YOUR_DEEPSEEK_API_KEY" // Replace with your actual Deepseek API key func main() { http.HandleFunc("/", handleRequest) port := os.Getenv("PORT") if port == "" { port = "8080" // Default port } fmt.Printf("Server listening on port %s\n", port) log.Fatal(http.ListenAndServe(":"+port, nil)) } func handleRequest(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } // Decode the incoming JSON request var requestPayload RequestPayload err := json.NewDecoder(r.Body).Decode(&requestPayload) if err != nil { http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest) return } // Forward the request to the Deepseek API deepseekResponse, err := forwardToDeepseek(requestPayload) if err != nil { http.Error(w, "Error forwarding to Deepseek: "+err.Error(), http.StatusInternalServerError) return } // Encode the Deepseek response as JSON and send it back to the client w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(deepseekResponse) if err != nil { http.Error(w, "Error encoding response: "+err.Error(), http.StatusInternalServerError) return } } func forwardToDeepseek(requestPayload RequestPayload) (ResponsePayload, error) { // Prepare the request to Deepseek requestBody, err := json.Marshal(map[string]string{"prompt": requestPayload.Question}) // Adjust the payload as needed for Deepseek if err != nil { return ResponsePayload{}, fmt.Errorf("error marshaling request to Deepseek: %w", err) } req, err := http.NewRequest(http.MethodPost, deepseekAPIEndpoint, bytes.NewBuffer(requestBody)) if err != nil { return ResponsePayload{}, fmt.Errorf("error creating Deepseek request: %w", err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+deepseekAPIKey) // Add API key if required // Send the request to Deepseek client := &http.Client{} resp, err := client.Do(req) if err != nil { return ResponsePayload{}, fmt.Errorf("error sending request to Deepseek: %w", err) } defer resp.Body.Close() // Read the response from Deepseek body, err := io.ReadAll(resp.Body) if err != nil { return ResponsePayload{}, fmt.Errorf("error reading Deepseek response: %w", err) } if resp.StatusCode != http.StatusOK { return ResponsePayload{}, fmt.Errorf("Deepseek API returned error: %s, status code: %d", string(body), resp.StatusCode) } // Decode the Deepseek response var deepseekResponse ResponsePayload err = json.Unmarshal(body, &deepseekResponse) if err != nil { return ResponsePayload{}, fmt.Errorf("error unmarshaling Deepseek response: %w", err) } return deepseekResponse, nil } ``` **How to Run:** 1. **Save:** Save the code as `main.go`. 2. **Dependencies:** Make sure you have Go installed. You don't need to install any external dependencies for this example, as it uses only the standard library. 3. **Replace Placeholders:** **Crucially, replace `"https://api.deepseek.com/v1/completions"` and `"YOUR_DEEPSEEK_API_KEY"` with the actual Deepseek API endpoint and your API key.** 4. **Run:** Open a terminal, navigate to the directory where you saved `main.go`, and run `go run main.go`. 5. **Test:** Use a tool like `curl` or Postman to send a POST request to `http://localhost:8080/` (or the port you configured). The request body should be JSON like this: ```json { "question": "What is the capital of France?" } ``` **Example `curl` command:** ```bash curl -X POST -H "Content-Type: application/json" -d '{"question": "What is the capital of France?"}' http://localhost:8080/ ``` **Explanation:** 1. **`main` Function:** * Sets up an HTTP handler that listens for requests on the root path (`/`). * Starts the HTTP server on port 8080 (or the port specified by the `PORT` environment variable). 2. **`handleRequest` Function:** * Checks if the request method is POST. * Decodes the JSON request body into a `RequestPayload` struct. * Calls `forwardToDeepseek` to send the question to the Deepseek API. * Encodes the Deepseek response as JSON and sends it back to the client. * Handles errors appropriately. 3. **`forwardToDeepseek` Function:** * Marshals the `RequestPayload` into a JSON payload suitable for the Deepseek API. **You'll need to adjust the structure of this payload to match the Deepseek API's requirements.** * Creates an HTTP request to the Deepseek API endpoint. * Sets the `Content-Type` header to `application/json`. * **Adds the Deepseek API key to the `Authorization` header (if required).** * Sends the request to the Deepseek API. * Reads the response from the Deepseek API. * Decodes the JSON response into a `ResponsePayload` struct. * Handles errors appropriately. **Chinese Translation of Key Concepts:** * **MCP Server:** MCP 服务器 (MCP fúwùqì) * **Redirect:** 重定向 (chóngdìngxiàng) * **Deepseek Model:** Deepseek 模型 (Deepseek móxíng) * **API Endpoint:** API 端点 (API duāndiǎn) * **JSON:** JSON (pronounced the same in Chinese) * **Request:** 请求 (qǐngqiú) * **Response:** 响应 (xiǎngyìng) * **Error Handling:** 错误处理 (cuòwù chǔlǐ) * **Concurrency:** 并发 (bìngfā) * **Authentication:** 身份验证 (shēnfèn yànzhèng) * **Authorization:** 授权 (shòuquán) * **Payload:** 负载 (fùzài) * **Goroutine:** Goroutine (pronounced the same in Chinese) **Further Improvements:** * **Configuration:** Use environment variables or a configuration file to store the Deepseek API endpoint, API key, and other settings. * **Logging:** Implement more robust logging using a library like `logrus` or `zap`. * **Metrics:** Add metrics to track the number of requests, response times, and error rates. * **Rate Limiting:** Implement rate limiting to prevent abuse of the Deepseek API. * **Caching:** Cache responses from the Deepseek API to improve performance and reduce costs. * **Health Checks:** Add a health check endpoint to monitor the server's status. * **Load Balancing:** If you need to handle a large volume of traffic, consider using a load balancer to distribute requests across multiple instances of the server. * **Input Validation:** Thoroughly validate the incoming `question` to prevent injection attacks or other security vulnerabilities. Remember to adapt the code to the specific requirements of the Deepseek API you are using. Good luck!

chew-z

研究与数据
访问服务器

README

DeepSeek MCP 服务器

一个生产级别的 MCP 服务器,集成了 DeepSeek 的 API,具有高级代码审查功能、高效的文件管理和 API 账户管理。

特性

  • 多模型支持: 从各种 DeepSeek 模型中选择,包括 DeepSeek Chat 和 DeepSeek Coder
  • 代码审查重点: 内置系统提示,用于详细的代码分析,并以 markdown 格式输出
  • 自动文件处理: 内置文件管理,可直接集成文件路径
  • API 账户管理: 检查余额并估算 token 使用量
  • JSON 模式支持: 请求结构化的 JSON 响应,便于解析
  • 高级错误处理: 优雅降级,并提供结构化的错误日志记录
  • 改进的重试逻辑: 自动重试 API 调用,并具有可配置的指数退避
  • 安全性: 可配置的文件类型限制和大小限制
  • 性能监控: 内置指标收集,用于请求延迟和吞吐量

前提条件

  • Go 1.21+
  • DeepSeek API 密钥
  • MCP 协议的基本理解

安装 & 快速开始

# 克隆和构建
git clone https://github.com/your-username/DeepseekMCP
cd DeepseekMCP
go build -o bin/mcp-deepseek

# 使用环境变量启动服务器
export DEEPSEEK_API_KEY=your_api_key
export DEEPSEEK_MODEL=deepseek-chat
./bin/mcp-deepseek

配置

Claude Desktop

{
  "mcpServers": {
    "deepseek": {
      "command": "/Your/project/path/bin/mcp-deepseek",
      "env": {
        "DEEPSEEK_API_KEY": "YOUR_API_KEY",
        "DEEPSEEK_MODEL": "deepseek-chat"
      }
    }
  }
}

环境变量

变量 描述 默认值
DEEPSEEK_API_KEY DeepSeek API 密钥 必需
DEEPSEEK_MODEL 可用模型的模型 ID deepseek-chat
DEEPSEEK_SYSTEM_PROMPT 代码审查的系统提示 默认代码审查提示
DEEPSEEK_SYSTEM_PROMPT_FILE 包含系统提示的文件的路径
DEEPSEEK_MAX_FILE_SIZE 最大上传大小(字节) 10485760 (10MB)
DEEPSEEK_ALLOWED_FILE_TYPES 逗号分隔的 MIME 类型 [常见文本/代码类型]
DEEPSEEK_TIMEOUT API 超时时间(秒) 90
DEEPSEEK_MAX_RETRIES 最大 API 重试次数 2
DEEPSEEK_INITIAL_BACKOFF 初始退避时间(秒) 1
DEEPSEEK_MAX_BACKOFF 最大退避时间(秒) 10
DEEPSEEK_TEMPERATURE 模型温度 (0.0-1.0) 0.4

.env 示例:

DEEPSEEK_API_KEY=your_api_key
DEEPSEEK_MODEL=deepseek-chat
DEEPSEEK_SYSTEM_PROMPT="Your custom code review prompt here"
# Alternative: load system prompt from file
# DEEPSEEK_SYSTEM_PROMPT_FILE=/path/to/prompt.txt
DEEPSEEK_MAX_FILE_SIZE=5242880  # 5MB
DEEPSEEK_ALLOWED_FILE_TYPES=text/x-go,text/markdown
DEEPSEEK_TEMPERATURE=0.7

核心 API 工具

目前,服务器提供以下工具:

deepseek_ask

用于代码分析、审查和一般查询,可以选择包含文件路径。

{
  "name": "deepseek_ask",
  "arguments": {
    "query": "Review this Go code for concurrency issues...",
    "model": "deepseek-chat",
    "systemPrompt": "Optional custom review instructions",
    "file_paths": ["main.go", "config.go"],
    "json_mode": false
  }
}

deepseek_models

列出所有可用的 DeepSeek 模型及其功能。

{
  "name": "deepseek_models",
  "arguments": {}
}

deepseek_balance

检查您的 DeepSeek API 账户余额和可用性状态。

{
  "name": "deepseek_balance",
  "arguments": {}
}

deepseek_token_estimate

估算文本或文件的 token 数量,以帮助进行配额管理。

{
  "name": "deepseek_token_estimate",
  "arguments": {
    "text": "Your text to estimate...",
    "file_path": "path/to/your/file.go"
  }
}

支持的模型

默认情况下支持以下 DeepSeek 模型:

模型 ID 描述
deepseek-chat 通用聊天模型,平衡了性能和效率
deepseek-coder 专门用于编码和技术任务的模型
deepseek-reasoner 针对推理和解决问题任务优化的模型

注意:实际可用的模型可能因您的 API 访问级别而异。服务器将自动发现并提供您通过 DeepSeek API 访问的所有模型。

支持的文件类型

扩展名 MIME 类型
.go text/x-go
.py text/x-python
.js text/javascript
.md text/markdown
.java text/x-java
.c/.h text/x-c
.cpp/.hpp text/x-c++
25+ 更多 (参见 deepseek.go 中的 getMimeTypeFromPath)

运行说明

  • 降级模式: 在初始化错误时自动进入安全模式
  • 审计日志: 所有操作都记录时间戳和元数据
  • 安全性: 在处理之前,通过 MIME 类型和大小验证文件内容

文件处理

服务器直接通过 deepseek_ask 工具处理文件:

  1. file_paths 数组参数中指定本地文件路径
  2. 服务器自动执行以下操作:
    • 从提供的路径读取文件
    • 根据文件扩展名确定正确的 MIME 类型
    • 将文件内容上传到 DeepSeek API
    • 使用文件作为查询的上下文

这种直接文件处理方法消除了对单独的文件上传/管理端点的需求。

JSON 模式支持

对于需要结构化数据输出的集成,服务器支持 JSON 模式:

  • 结构化响应: 从 DeepSeek 模型请求格式正确的 JSON 响应
  • 解析器友好: 非常适合 CI/CD 管道和自动化系统
  • 易于集成: 只需在您的请求中设置 json_mode: true

使用 JSON 模式的示例:

{
  "name": "deepseek_ask",
  "arguments": {
    "query": "Analyze this code and return a JSON object with: issues_found (array of strings), complexity_score (number 1-10), and recommendations (array of strings)",
    "model": "deepseek-chat",
    "json_mode": true,
    "file_paths": ["main.go", "config.go"]
  }
}

这将返回一个格式良好的 JSON 响应,可以直接由您的应用程序解析。

开发

命令行选项

服务器支持以下命令行选项来覆盖环境变量:

# 覆盖要使用的 DeepSeek 模型
./bin/mcp-deepseek -deepseek-model=deepseek-coder

# 覆盖系统提示
./bin/mcp-deepseek -deepseek-system-prompt="Your custom prompt here"

# 覆盖温度设置 (0.0-1.0)
./bin/mcp-deepseek -deepseek-temperature=0.8

运行测试

要运行测试:

go test -v ./...

运行 Linter

golangci-lint run

格式化代码

gofmt -w .

许可证

MIT 许可证

贡献

欢迎贡献!请随时提交 Pull Request。

  1. Fork 项目
  2. 创建您的功能分支 (git checkout -b feature/amazing-feature)
  3. 提交您的更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 打开一个 Pull Request

推荐服务器

Crypto Price & Market Analysis MCP Server

Crypto Price & Market Analysis MCP Server

一个模型上下文协议 (MCP) 服务器,它使用 CoinCap API 提供全面的加密货币分析。该服务器通过一个易于使用的界面提供实时价格数据、市场分析和历史趋势。 (Alternative, slightly more formal and technical translation): 一个模型上下文协议 (MCP) 服务器,利用 CoinCap API 提供全面的加密货币分析服务。该服务器通过用户友好的界面,提供实时价格数据、市场分析以及历史趋势数据。

精选
TypeScript
MCP PubMed Search

MCP PubMed Search

用于搜索 PubMed 的服务器(PubMed 是一个免费的在线数据库,用户可以在其中搜索生物医学和生命科学文献)。 我是在 MCP 发布当天创建的,但当时正在度假。 我看到有人在您的数据库中发布了类似的服务器,但还是决定发布我的服务器。

精选
Python
mixpanel

mixpanel

连接到您的 Mixpanel 数据。 从 Mixpanel 分析查询事件、留存和漏斗数据。

精选
TypeScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

精选
Python
Nefino MCP Server

Nefino MCP Server

为大型语言模型提供访问德国可再生能源项目新闻和信息的能力,允许按地点、主题(太阳能、风能、氢能)和日期范围进行筛选。

官方
Python
Vectorize

Vectorize

将 MCP 服务器向量化以实现高级检索、私有深度研究、Anything-to-Markdown 文件提取和文本分块。

官方
JavaScript
Mathematica Documentation MCP server

Mathematica Documentation MCP server

一个服务器,通过 FastMCP 提供对 Mathematica 文档的访问,使用户能够从 Wolfram Mathematica 检索函数文档和列出软件包符号。

本地
Python
kb-mcp-server

kb-mcp-server

一个 MCP 服务器,旨在实现便携性、本地化、简易性和便利性,以支持对 txtai “all in one” 嵌入数据库进行基于语义/图的检索。任何 tar.gz 格式的 txtai 嵌入数据库都可以被加载。

本地
Python
Research MCP Server

Research MCP Server

这个服务器用作 MCP 服务器,与 Notion 交互以检索和创建调查数据,并与 Claude Desktop Client 集成以进行和审查调查。

本地
Python
Cryo MCP Server

Cryo MCP Server

一个API服务器,实现了模型补全协议(MCP),用于Cryo区块链数据提取,允许用户通过任何兼容MCP的客户端查询以太坊区块链数据。

本地
Python