Add files via upload

This commit is contained in:
公明 authored and GitHub committed 2026-02-04 01:57:01 +08:00
1 parent 3cbf398636
commit a27c13b734
2 files changed
+14 -3

No files matched your search

+3 -1
View File
@@ -464,7 +464,9 @@ func createSDKClient(ctx context.Context, serverCfg config.ExternalMCPServerConf
if serverCfg.Command == "" { if serverCfg.Command == "" {
return nil, fmt.Errorf("stdio 模式需要配置 command") return nil, fmt.Errorf("stdio 模式需要配置 command")
} }
cmd := exec.CommandContext(ctx, serverCfg.Command, serverCfg.Args...) // 使用 ctx 控制超时与取消 // 必须用 exec.Command 而非 CommandContext:doConnect 返回后 ctx 会被 cancel,
// 若用 CommandContext(ctx) 会立刻杀掉子进程,导致 ListTools 等后续请求失败、显示 0 工具
cmd := exec.Command(serverCfg.Command, serverCfg.Args...)
if len(serverCfg.Env) > 0 { if len(serverCfg.Env) > 0 {
cmd.Env = append(cmd.Env, envMapToSlice(serverCfg.Env)...) cmd.Env = append(cmd.Env, envMapToSlice(serverCfg.Env)...)
} }
+11 -2
View File
@@ -1,6 +1,7 @@
package mcp package mcp
import ( import (
"bufio"
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
@@ -368,6 +369,7 @@ func (s *Server) handleListTools(msg *Message) *Message {
tools = append(tools, tool) tools = append(tools, tool)
} }
s.mu.RUnlock() s.mu.RUnlock()
s.logger.Info("tools/list 请求", zap.Int("返回工具数", len(tools)))
response := ListToolsResponse{Tools: tools} response := ListToolsResponse{Tools: tools}
result, _ := json.Marshal(response) result, _ := json.Marshal(response)
@@ -1167,10 +1169,11 @@ func (s *Server) RegisterResource(resource *Resource) {
} }
// HandleStdio 处理标准输入输出(用于 stdio 传输模式) // HandleStdio 处理标准输入输出(用于 stdio 传输模式)
// MCP 协议使用换行分隔的 JSON-RPC 消息 // MCP 协议使用换行分隔的 JSON-RPC 消息;管道下需每次写入后 Flush,否则客户端会读不到响应
func (s *Server) HandleStdio() error { func (s *Server) HandleStdio() error {
decoder := json.NewDecoder(os.Stdin) decoder := json.NewDecoder(os.Stdin)
encoder := json.NewEncoder(os.Stdout) stdout := bufio.NewWriter(os.Stdout)
encoder := json.NewEncoder(stdout)
// 注意:不设置缩进,MCP 协议期望紧凑的 JSON 格式 // 注意:不设置缩进,MCP 协议期望紧凑的 JSON 格式
for { for {
@@ -1191,6 +1194,9 @@ func (s *Server) HandleStdio() error {
if err := encoder.Encode(errorMsg); err != nil { if err := encoder.Encode(errorMsg); err != nil {
return fmt.Errorf("发送错误响应失败: %w", err) return fmt.Errorf("发送错误响应失败: %w", err)
} }
if err := stdout.Flush(); err != nil {
return fmt.Errorf("刷新 stdout 失败: %w", err)
}
continue continue
} }
@@ -1206,6 +1212,9 @@ func (s *Server) HandleStdio() error {
if err := encoder.Encode(response); err != nil { if err := encoder.Encode(response); err != nil {
return fmt.Errorf("发送响应失败: %w", err) return fmt.Errorf("发送响应失败: %w", err)
} }
if err := stdout.Flush(); err != nil {
return fmt.Errorf("刷新 stdout 失败: %w", err)
}
} }
return nil return nil