-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcp_client.go
191 lines (166 loc) · 4.86 KB
/
mcp_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"bufio"
"context"
"fmt"
"io"
"log/slog"
"sync"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/mcp"
)
// MCPClient provides an interface to external MCP servers
type MCPClient struct {
config *MCPClientConfig
client *client.StdioMCPClient
logger *slog.Logger
stderrCancel context.CancelFunc
initOnce sync.Once // Ensures monitoring starts only once during Initialize
closeOnce sync.Once // Ensures close operation is performed only once
}
// NewMCPClient creates a new MCP client
func NewMCPClient(config *MCPClientConfig) (*MCPClient, error) {
// Convert map[string]string to []string for environment variables
env := make([]string, 0, len(config.Env))
for k, v := range config.Env {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
c, err := client.NewStdioMCPClient(
config.Command,
env,
config.Args...,
)
if err != nil {
return nil, fmt.Errorf("failed to create MCP client: %w", err)
}
return &MCPClient{
config: config,
client: c,
logger: WithComponent("mcp_client"),
}, nil
}
func (c *MCPClient) Initialize(ctx context.Context) (*mcp.InitializeResult, error) {
// Start stderr monitoring once when Initialize is successful
c.initOnce.Do(func() {
stderrCtx, cancel := context.WithCancel(ctx)
c.stderrCancel = cancel
go c.captureStderr(stderrCtx)
c.logger.Debug("stderr capture goroutine started")
})
initRequest := mcp.InitializeRequest{}
initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
initRequest.Params.ClientInfo = mcp.Implementation{
Name: "mcp-http-proxy",
Version: "1.0.0",
}
resp, err := c.client.Initialize(ctx, initRequest)
if err != nil {
return nil, fmt.Errorf("failed to initialize: %w", err)
}
return resp, nil
}
func (c *MCPClient) captureStderr(ctx context.Context) {
stderr := c.client.Stderr()
scanner := bufio.NewScanner(stderr)
for {
select {
case <-ctx.Done():
c.logger.Debug("stderr capture stopped due to context cancellation")
return
default:
if !scanner.Scan() {
if err := scanner.Err(); err != nil && err != io.EOF && err != context.Canceled {
c.logger.Error("error reading from stderr", "error", err)
} else {
c.logger.Debug("stderr stream closed or scanner finished")
}
return // Exit on error or EOF
}
line := scanner.Text()
c.logger.Warn("subprocess stderr", "message", line)
}
}
}
func (c *MCPClient) ListTools(ctx context.Context) ([]mcp.Tool, error) {
req := mcp.ListToolsRequest{}
resp, err := c.client.ListTools(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to list tools: %w", err)
}
// Skip filtering if no extensions are configured
if c.config.Extensions == nil {
return resp.Tools, nil
}
// Filter tools based on allow/deny lists
var filteredTools []mcp.Tool
for _, tool := range resp.Tools {
if c.isToolAllowed(tool.Name) {
filteredTools = append(filteredTools, tool)
}
}
return filteredTools, nil
}
func (c *MCPClient) CallTool(ctx context.Context, name string, args map[string]interface{}) (*mcp.CallToolResult, error) {
// Check tool restrictions
if c.config.Extensions != nil && !c.isToolAllowed(name) {
logger := WithComponent("mcp_client")
logger.Warn("Tool access denied", "tool", name)
return nil, fmt.Errorf("tool %s is not allowed", name)
}
req := mcp.CallToolRequest{}
req.Params.Name = name
req.Params.Arguments = args
resp, err := c.client.CallTool(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to call tool: %w", err)
}
return resp, nil
}
// isToolAllowed checks if the tool is allowed to be called
func (c *MCPClient) isToolAllowed(toolName string) bool {
ext := c.config.Extensions
if ext == nil {
return true
}
// If allow list is specified, only allow tools in the list
if len(ext.Tools.Allow) > 0 {
for _, allowed := range ext.Tools.Allow {
if allowed == toolName {
return true
}
}
return false
}
// If no allow list but deny list exists, allow tools not in deny list
if len(ext.Tools.Deny) > 0 {
for _, denied := range ext.Tools.Deny {
if denied == toolName {
return false
}
}
}
// If neither list is specified, allow all tools
return true
}
// Close closes the connection to the MCP client
func (c *MCPClient) Close() error {
var err error
c.closeOnce.Do(func() {
if c.stderrCancel != nil {
c.logger.Debug("cancelling stderr capture")
c.stderrCancel()
c.stderrCancel = nil // Prevent being called again
}
c.logger.Debug("closing underlying stdio client")
err = c.client.Close()
if err != nil {
c.logger.Error("error closing stdio client", "error", err)
}
})
return err
}
// Call executes a request via the MCP client
func (c *MCPClient) Call(functionName string, params map[string]interface{}) (interface{}, error) {
// In the actual implementation, this would handle the request to the external process
return nil, fmt.Errorf("not implemented")
}