Repository navigation
Expand file tree
/
Copy pathcall_cmd.go
More file actions
563 lines (477 loc) Β· 20 KB
/
Copy pathcall_cmd.go
File metadata and controls
563 lines (477 loc) Β· 20 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cache"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cli/output"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/index"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/secret"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/server"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/storage"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/truncate"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
// Call command output format constants (kept for backward compatibility)
// Note: "pretty" is the default for call command (different from global "table" default)
const (
outputFormatJSON = "json"
outputFormatPretty = "pretty"
)
var (
callCmd = &cobra.Command{
Use: "call",
Short: "Call tools on upstream servers",
Long: "Commands for calling tools on upstream MCP servers",
}
callToolCmd = &cobra.Command{
Use: "tool",
Short: "[REMOVED] Use 'call tool-read', 'call tool-write', or 'call tool-destructive'",
Long: `[REMOVED] The legacy 'call tool' command has been removed.
Use the intent-based variants instead:
- mcpproxy call tool-read For read-only operations (search, query, list, get)
- mcpproxy call tool-write For state-modifying operations (create, update, send)
- mcpproxy call tool-destructive For irreversible operations (delete, remove, drop)
Examples:
# Read operations
mcpproxy call tool-read --tool-name=github:list_repos --json_args='{}'
# Write operations
mcpproxy call tool-write --tool-name=github:create_issue --json_args='{"title":"Bug"}'
# Destructive operations
mcpproxy call tool-destructive --tool-name=github:delete_repo --json_args='{"repo":"test"}'`,
RunE: runCallTool,
}
// Intent-based tool variant commands (Spec 018)
callToolReadCmd = &cobra.Command{
Use: "tool-read",
Short: "Call a tool with read-only intent",
Long: `Call a tool on an upstream server with read-only intent declaration.
This command is for operations that only read data without making changes.
The intent is automatically set to operation_type="read".
IDEs can configure this command for auto-approval of read operations.
Examples:
# Read data from a server
mcpproxy call tool-read --tool-name=github:list_repos --json_args='{"owner":"user"}'
# With optional reason
mcpproxy call tool-read --tool-name=weather:get_forecast --json_args='{"city":"NYC"}' --reason="Checking weather for trip planning"
# With data sensitivity classification
mcpproxy call tool-read --tool-name=db:query_users --json_args='{}' --sensitivity=internal`,
RunE: runCallToolRead,
}
callToolWriteCmd = &cobra.Command{
Use: "tool-write",
Short: "Call a tool with write intent",
Long: `Call a tool on an upstream server with write intent declaration.
This command is for operations that create or modify data.
The intent is automatically set to operation_type="write".
IDEs typically prompt for approval before executing write operations.
Examples:
# Create a new issue
mcpproxy call tool-write --tool-name=github:create_issue --json_args='{"title":"Bug report","body":"..."}'
# Update a record with reason
mcpproxy call tool-write --tool-name=db:update_user --json_args='{"id":123,"name":"New Name"}' --reason="Correcting user profile"`,
RunE: runCallToolWrite,
}
callToolDestructiveCmd = &cobra.Command{
Use: "tool-destructive",
Short: "Call a tool with destructive intent",
Long: `Call a tool on an upstream server with destructive intent declaration.
This command is for operations that delete data or have irreversible effects.
The intent is automatically set to operation_type="destructive".
IDEs should always prompt for explicit confirmation before executing.
Examples:
# Delete a repository
mcpproxy call tool-destructive --tool-name=github:delete_repo --json_args='{"repo":"old-project"}'
# Drop a database table with reason
mcpproxy call tool-destructive --tool-name=db:drop_table --json_args='{"table":"temp_data"}' --reason="Cleanup after migration"`,
RunE: runCallToolDestructive,
}
// Command flags for call tool
callToolName string
callJSONArgs string
callLogLevel string
callConfigPath string
callTimeout time.Duration
callOutputFormat string
// Intent flags for tool variant commands
callIntentReason string
callIntentSensitivity string
)
// GetCallCommand returns the call command for adding to the root command
func GetCallCommand() *cobra.Command {
return callCmd
}
func init() {
// Add tool subcommands to call command
callCmd.AddCommand(callToolCmd)
callCmd.AddCommand(callToolReadCmd)
callCmd.AddCommand(callToolWriteCmd)
callCmd.AddCommand(callToolDestructiveCmd)
// Define flags for legacy call tool command
callToolCmd.Flags().StringVarP(&callToolName, "tool-name", "t", "", "Tool name in format server:tool_name (required)")
callToolCmd.Flags().StringVarP(&callJSONArgs, "json_args", "j", "{}", "JSON arguments for the tool (default: {})")
callToolCmd.Flags().StringVarP(&callLogLevel, "log-level", "l", "info", "Log level (trace, debug, info, warn, error)")
addConfigFlag(callToolCmd.Flags(), &callConfigPath, "Path to MCP configuration file (default: ~/.mcpproxy/mcp_config.json)")
callToolCmd.Flags().DurationVar(&callTimeout, "timeout", 30*time.Second, "Tool call timeout")
callToolCmd.Flags().StringVarP(&callOutputFormat, "output", "o", "pretty", "Output format (pretty, json)")
// Mark required flags for legacy command
err := callToolCmd.MarkFlagRequired("tool-name")
if err != nil {
panic(fmt.Sprintf("Failed to mark tool-name flag as required: %v", err))
}
// Add examples and usage help for legacy command
callToolCmd.Example = ` # Call built-in tools (no server prefix)
mcpproxy call tool --tool-name=upstream_servers --json_args='{"operation":"list"}'
mcpproxy call tool --tool-name=retrieve_tools --json_args='{"query":"github repositories"}'
# Call external server tools (server:tool format)
mcpproxy call tool --tool-name=github-server:list_repos --json_args='{"owner":"myorg"}'
# Use custom config file
mcpproxy call tool --tool-name=upstream_servers --json_args='{"operation":"list"}' --config=/path/to/config.json`
// Setup flags for intent-based tool variant commands
setupToolVariantFlags(callToolReadCmd)
setupToolVariantFlags(callToolWriteCmd)
setupToolVariantFlags(callToolDestructiveCmd)
}
// setupToolVariantFlags adds common flags to a tool variant command
func setupToolVariantFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&callToolName, "tool-name", "t", "", "Tool name in format server:tool_name (required)")
cmd.Flags().StringVarP(&callJSONArgs, "json_args", "j", "{}", "JSON arguments for the tool (default: {})")
cmd.Flags().StringVarP(&callLogLevel, "log-level", "l", "info", "Log level (trace, debug, info, warn, error)")
addConfigFlag(cmd.Flags(), &callConfigPath, "Path to MCP configuration file (default: ~/.mcpproxy/mcp_config.json)")
cmd.Flags().DurationVar(&callTimeout, "timeout", 30*time.Second, "Tool call timeout")
cmd.Flags().StringVarP(&callOutputFormat, "output", "o", "pretty", "Output format (pretty, json)")
// Intent-specific flags
cmd.Flags().StringVar(&callIntentReason, "reason", "", "Human-readable explanation for the operation (max 1000 chars)")
cmd.Flags().StringVar(&callIntentSensitivity, "sensitivity", "", "Data sensitivity classification: public, internal, private, unknown")
// Mark required flags
if err := cmd.MarkFlagRequired("tool-name"); err != nil {
panic(fmt.Sprintf("Failed to mark tool-name flag as required: %v", err))
}
}
func runCallTool(_ *cobra.Command, _ []string) error {
return fmt.Errorf(`the legacy 'call tool' command has been removed
Use the intent-based variants instead:
mcpproxy call tool-read For read-only operations
mcpproxy call tool-write For state-modifying operations
mcpproxy call tool-destructive For irreversible operations
Example:
mcpproxy call tool-read --tool-name=github:list_repos --json_args='{}'`)
}
// loadCallConfig loads the MCP configuration file for call command
func loadCallConfig() (*config.Config, error) {
configFilePath := resolveCLIConfigPath(callConfigPath)
if configFilePath == "" {
var err error
if configFilePath, err = defaultHomeConfigPath(); err != nil {
return nil, err
}
}
// Check if config file exists
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
return nil, fmt.Errorf("configuration file not found at %s. Please run 'mcpproxy' daemon first to create the config", configFilePath)
}
// Load configuration using file-based loading
globalConfig, err := config.LoadFromFile(configFilePath)
if err != nil {
return nil, fmt.Errorf("failed to load config from %s: %w", configFilePath, err)
}
// Respect global --data-dir flag
if dataDir != "" {
globalConfig.DataDir = dataDir
}
return globalConfig, nil
}
// outputCallResultAsJSON outputs the result in JSON format using unified formatter
func outputCallResultAsJSON(result interface{}) error {
formatter := &output.JSONFormatter{Indent: true}
formatted, err := formatter.Format(result)
if err != nil {
return fmt.Errorf("failed to format result as JSON: %w", err)
}
fmt.Println(formatted)
return nil
}
// outputCallResultPretty outputs the result in a human-readable format
func outputCallResultPretty(result interface{}) {
fmt.Printf("π Tool Result:\n")
fmt.Printf("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n")
// Handle the result based on its type
switch v := result.(type) {
case map[string]interface{}:
// Pretty print map content
if content, exists := v["content"]; exists {
if contentList, ok := content.([]interface{}); ok {
for i, item := range contentList {
if itemMap, ok := item.(map[string]interface{}); ok {
if text, ok := itemMap["text"].(string); ok {
fmt.Printf("Content %d: %s\n", i+1, text)
} else {
fmt.Printf("Content %d: %+v\n", i+1, item)
}
} else {
fmt.Printf("Content %d: %+v\n", i+1, item)
}
}
} else {
fmt.Printf("Content: %+v\n", content)
}
} else {
// Pretty print the entire map
for key, value := range v {
fmt.Printf("%s: %+v\n", key, value)
}
}
default:
// Fallback to JSON for unknown types
output, err := json.MarshalIndent(result, "", " ")
if err != nil {
fmt.Printf("Raw result: %+v\n", result)
} else {
fmt.Println(string(output))
}
}
fmt.Printf("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n")
}
func outputPrettyCallResult(result interface{}, isError bool) error {
if isError {
fmt.Fprintln(os.Stderr, "β οΈ Tool call returned an error.")
outputCallResultPretty(result)
return callResultError{}
}
fmt.Fprintf(os.Stderr, "β
Tool call completed successfully!\n\n")
outputCallResultPretty(result)
return nil
}
// createLogger creates a zap logger with the specified level
func createLogger(level string) (*zap.Logger, error) {
var zapLevel zap.AtomicLevel
switch strings.ToLower(level) {
case "trace", "debug":
zapLevel = zap.NewAtomicLevelAt(zap.DebugLevel)
case "info":
zapLevel = zap.NewAtomicLevelAt(zap.InfoLevel)
case "warn":
zapLevel = zap.NewAtomicLevelAt(zap.WarnLevel)
case "error":
zapLevel = zap.NewAtomicLevelAt(zap.ErrorLevel)
default:
zapLevel = zap.NewAtomicLevelAt(zap.InfoLevel)
}
config := zap.Config{
Level: zapLevel,
Development: false,
Encoding: "console",
EncoderConfig: zap.NewDevelopmentEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
return config.Build()
}
// runCallToolRead handles the tool-read command (Spec 018)
func runCallToolRead(cmd *cobra.Command, _ []string) error {
return runCallToolVariant(cmd, "call_tool_read", "read")
}
// runCallToolWrite handles the tool-write command (Spec 018)
func runCallToolWrite(cmd *cobra.Command, _ []string) error {
return runCallToolVariant(cmd, "call_tool_write", "write")
}
// runCallToolDestructive handles the tool-destructive command (Spec 018)
func runCallToolDestructive(cmd *cobra.Command, _ []string) error {
return runCallToolVariant(cmd, "call_tool_destructive", "destructive")
}
// runCallToolVariant is the common implementation for intent-based tool calls
func runCallToolVariant(cmd *cobra.Command, toolVariant, operationType string) (callErr error) {
// Cobra validates required flags before RunE. Runtime failures in JSON mode
// get one machine-readable document on stdout and retain a nonzero exit.
if callOutputFormat == outputFormatJSON {
cmd.SilenceUsage = true
defer func() {
var resultErr callResultError
if callErr != nil && !errors.As(callErr, &resultErr) {
writeCallJSONError(callErr)
}
}()
}
ctx, cancel := context.WithTimeout(context.Background(), callTimeout)
defer cancel()
// Parse JSON arguments
var toolArgs map[string]interface{}
if err := json.Unmarshal([]byte(callJSONArgs), &toolArgs); err != nil {
return fmt.Errorf("invalid JSON arguments: %w", err)
}
// Build arguments for the tool variant with flat intent params
variantArgs := map[string]interface{}{
"name": callToolName,
"args": toolArgs,
}
// Add flat intent params (operation_type is inferred from tool variant)
if callIntentSensitivity != "" {
variantArgs["intent_data_sensitivity"] = callIntentSensitivity
}
if callIntentReason != "" {
variantArgs["intent_reason"] = callIntentReason
}
// Load configuration
globalConfig, err := loadCallConfig()
if err != nil {
return fmt.Errorf("failed to load configuration: %w", err)
}
// Create logger
logger, err := createLogger(callLogLevel)
if err != nil {
return fmt.Errorf("failed to create logger: %w", err)
}
// Display intent information on stderr so machine formats (-o json)
// keep stdout parseable (see docs/cli-output-formatting.md).
fmt.Fprintf(os.Stderr, "π Intent-Based Tool Call\n")
fmt.Fprintf(os.Stderr, " Tool: %s\n", callToolName)
fmt.Fprintf(os.Stderr, " Variant: %s (operation_type=%s)\n", toolVariant, operationType)
if callIntentSensitivity != "" {
fmt.Fprintf(os.Stderr, " Sensitivity: %s\n", callIntentSensitivity)
}
if callIntentReason != "" {
fmt.Fprintf(os.Stderr, " Reason: %s\n", callIntentReason)
}
fmt.Fprintf(os.Stderr, "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n")
// Detect daemon (socket first, then TCP fallback) and use client mode if available
if client, ok := newDaemonClient(globalConfig, logger.Sugar()); ok {
logger.Info("Detected running daemon, using client mode")
return runCallToolVariantClientMode(client, toolVariant, variantArgs, logger)
}
// No daemon - use standalone mode
logger.Info("No daemon detected, using standalone mode")
return runCallToolVariantStandalone(ctx, toolVariant, variantArgs, globalConfig)
}
// callResultError retains the nonzero process status after a complete MCP
// isError result has already been written to stdout.
type callResultError struct{}
func (callResultError) Error() string { return "tool returned an error result" }
type callDaemonError struct{ cause error }
func (e callDaemonError) Error() string {
return "failed to call tool via daemon: " + formatErrorWithRequestID(e.cause)
}
func (e callDaemonError) Unwrap() error { return e.cause }
func writeCallJSONError(err error) {
structured := output.NewStructuredError(output.ErrCodeOperationFailed, err.Error())
var apiErr *cliclient.APIError
if errors.As(err, &apiErr) && apiErr.RequestID != "" {
structured = structured.WithRequestID(apiErr.RequestID)
}
_ = outputCallResultAsJSON(structured)
}
// runCallToolVariantClientMode calls tool variant via the daemon HTTP API
func runCallToolVariantClientMode(client *cliclient.Client, toolVariant string, args map[string]interface{}, logger *zap.Logger) error {
// Ping daemon to verify connectivity
pingCtx, pingCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer pingCancel()
if err := client.Ping(pingCtx); err != nil {
logger.Warn("Failed to ping daemon, falling back to standalone mode",
zap.Error(err))
// Fall back to standalone mode
cfg, _ := loadCallConfig()
standaloneCtx := context.Background()
return runCallToolVariantStandalone(standaloneCtx, toolVariant, args, cfg)
}
fmt.Fprintf(os.Stderr, "βΉοΈ Using daemon mode - fast execution\n")
// Call tool via daemon
fmt.Fprintf(os.Stderr, "π Calling %s via daemon socket...\n", toolVariant)
callCtx, callCancel := context.WithTimeout(context.Background(), callTimeout)
defer callCancel()
// The daemon's CallTool expects a tool name and arguments
// For tool variants, we call the variant tool directly
result, err := client.CallTool(callCtx, toolVariant, args)
if err != nil {
// Keep the API error wrapped so JSON output can retain request_id.
return callDaemonError{cause: err}
}
// Output results based on format
switch callOutputFormat {
case outputFormatJSON:
if err := outputCallResultAsJSON(result); err != nil {
return err
}
if result.IsError {
return callResultError{}
}
return nil
case outputFormatPretty, "":
fallthrough
default:
return outputPrettyCallResult(result, result.IsError)
}
}
// runCallToolVariantStandalone calls tool variant directly without daemon
func runCallToolVariantStandalone(ctx context.Context, toolVariant string, args map[string]interface{}, globalConfig *config.Config) error {
fmt.Fprintf(os.Stderr, "β οΈ Using standalone mode - daemon not detected (slower startup)\n")
// Create logger with appropriate level
logger, err := createLogger(callLogLevel)
if err != nil {
return fmt.Errorf("failed to create logger: %w", err)
}
// Create storage manager
storageManager, err := storage.NewManager(globalConfig.DataDir, logger.Sugar())
if err != nil {
return fmt.Errorf("failed to create storage manager: %w", err)
}
defer storageManager.Close()
// Create index manager
indexManager, err := index.NewManager(globalConfig.DataDir, logger)
if err != nil {
return fmt.Errorf("failed to create index manager: %w", err)
}
defer indexManager.Close()
// Create secret resolver for command execution
secretResolver := secret.NewResolver()
// Create upstream manager
upstreamManager := upstream.NewManager(logger, globalConfig, storageManager.GetBoltDB(), secretResolver, storageManager)
// Create cache manager
cacheManager, err := cache.NewManager(storageManager.GetDB(), logger)
if err != nil {
return fmt.Errorf("failed to create cache manager: %w", err)
}
defer cacheManager.Close()
// Create truncator
truncator := truncate.NewTruncator(globalConfig.ToolResponseLimit)
// Create MCP proxy server
mcpProxy := server.NewMCPProxyServer(
storageManager,
indexManager,
upstreamManager,
cacheManager,
func() *truncate.Truncator { return truncator },
logger,
nil, // mainServer not needed for CLI calls
false,
globalConfig,
nil, // standalone one-shot: no runtime-owned signature cache
)
fmt.Fprintf(os.Stderr, "π οΈ Calling %s...\n", toolVariant)
// Call the tool variant through the proxy server's public method
result, err := mcpProxy.CallBuiltInTool(ctx, toolVariant, args)
if err != nil {
return fmt.Errorf("failed to call %s: %w", toolVariant, err)
}
// Output results based on format
switch callOutputFormat {
case outputFormatJSON:
if err := outputCallResultAsJSON(result); err != nil {
return err
}
if result.IsError {
return callResultError{}
}
return nil
case outputFormatPretty, "":
fallthrough
default:
return outputPrettyCallResult(result, result.IsError)
}
}