xonecas.io
60255
Zn

Zoea-Nova / files

Zoea-Nova / cmd / mcp_client / main.go

6.8 KB
1package main
2
3import (
4	"bufio"
5	"context"
6	"encoding/json"
7	"flag"
8	"fmt"
9	"os"
10	"regexp"
11	"strconv"
12	"strings"
13
14	"github.com/xonecas/zoea-nova/internal/config"
15	"github.com/xonecas/zoea-nova/internal/mcp"
16)
17
18// parseFunctionCall parses function-style calls like: tool_name(arg1, arg2, key=value)
19func parseFunctionCall(input string) (name string, args map[string]interface{}, ok bool) {
20	// Match pattern: function_name(args...)
21	re := regexp.MustCompile(`^(\w+)\((.*)\)$`)
22	matches := re.FindStringSubmatch(input)
23	if matches == nil {
24		return "", nil, false
25	}
26
27	name = matches[1]
28	argsStr := strings.TrimSpace(matches[2])
29	args = make(map[string]interface{})
30
31	if argsStr == "" {
32		return name, args, true
33	}
34
35	// Split arguments by comma, respecting quotes
36	argList := splitArgs(argsStr)
37
38	// Track positional argument index
39	positionalIndex := 0
40
41	for _, arg := range argList {
42		arg = strings.TrimSpace(arg)
43		if arg == "" {
44			continue
45		}
46
47		// Check if it's a key=value pair
48		if idx := strings.Index(arg, "="); idx > 0 {
49			key := strings.TrimSpace(arg[:idx])
50			value := strings.TrimSpace(arg[idx+1:])
51			args[key] = parseValue(value)
52		} else {
53			// Positional argument: use "arg0", "arg1", etc.
54			args[fmt.Sprintf("arg%d", positionalIndex)] = parseValue(arg)
55			positionalIndex++
56		}
57	}
58
59	return name, args, true
60}
61
62// splitArgs splits comma-separated arguments, respecting quoted strings
63func splitArgs(s string) []string {
64	var result []string
65	var current strings.Builder
66	inQuotes := false
67	quoteChar := rune(0)
68
69	for _, ch := range s {
70		switch {
71		case (ch == '"' || ch == '\'') && !inQuotes:
72			inQuotes = true
73			quoteChar = ch
74			current.WriteRune(ch)
75		case ch == quoteChar && inQuotes:
76			inQuotes = false
77			quoteChar = 0
78			current.WriteRune(ch)
79		case ch == ',' && !inQuotes:
80			result = append(result, current.String())
81			current.Reset()
82		default:
83			current.WriteRune(ch)
84		}
85	}
86
87	if current.Len() > 0 {
88		result = append(result, current.String())
89	}
90
91	return result
92}
93
94// parseValue parses a string value into appropriate type (string, number, bool, JSON object/array)
95func parseValue(s string) interface{} {
96	s = strings.TrimSpace(s)
97
98	// Try to parse as JSON first (for objects and arrays)
99	if (strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")) ||
100		(strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]")) {
101		var result interface{}
102		if err := json.Unmarshal([]byte(s), &result); err == nil {
103			return result
104		}
105	}
106
107	// Try boolean
108	if s == "true" {
109		return true
110	}
111	if s == "false" {
112		return false
113	}
114
115	// Try number
116	if num, err := strconv.ParseFloat(s, 64); err == nil {
117		// Return int if it's a whole number
118		if num == float64(int(num)) {
119			return int(num)
120		}
121		return num
122	}
123
124	// Try quoted string
125	if (strings.HasPrefix(s, `"`) && strings.HasSuffix(s, `"`)) ||
126		(strings.HasPrefix(s, `'`) && strings.HasSuffix(s, `'`)) {
127		return s[1 : len(s)-1]
128	}
129
130	// Return as-is (unquoted string)
131	return s
132}
133
134func main() {
135	configPath := flag.String("config", "config.toml", "Path to config file")
136	endpoint := flag.String("endpoint", "", "MCP server endpoint (overrides config)")
137	flag.Parse()
138
139	// Load config
140	cfg, err := config.Load(*configPath)
141	if err != nil {
142		fmt.Fprintf(os.Stderr, "Failed to load config: %v\n", err)
143		os.Exit(1)
144	}
145
146	// Use endpoint from config unless overridden by flag
147	mcpEndpoint := cfg.MCP.Upstream
148	if *endpoint != "" {
149		mcpEndpoint = *endpoint
150	}
151
152	ctx := context.Background()
153	client := mcp.NewClient(mcpEndpoint)
154
155	// Initialize connection
156	fmt.Printf("Connecting to %s...\n", mcpEndpoint)
157	clientInfo := map[string]interface{}{
158		"name":    "mcp_client",
159		"version": "1.0.0",
160	}
161
162	initResp, err := client.Initialize(ctx, clientInfo)
163	if err != nil {
164		fmt.Fprintf(os.Stderr, "Failed to initialize: %v\n", err)
165		os.Exit(1)
166	}
167
168	if initResp.Error != nil {
169		fmt.Fprintf(os.Stderr, "Initialization error: %s\n", initResp.Error.Message)
170		os.Exit(1)
171	}
172
173	fmt.Println("Connected successfully!")
174	fmt.Println()
175
176	// List available tools
177	tools, err := client.ListTools(ctx)
178	if err != nil {
179		fmt.Fprintf(os.Stderr, "Failed to list tools: %v\n", err)
180		os.Exit(1)
181	}
182
183	fmt.Printf("Available tools (%d):\n", len(tools))
184	for _, tool := range tools {
185		fmt.Printf("  - %s: %s\n", tool.Name, tool.Description)
186	}
187	fmt.Println()
188
189	// Interactive loop
190	fmt.Println("Enter tool calls:")
191	fmt.Println("  Function style: tool_name(arg1, arg2, key=value)")
192	fmt.Println("  JSON style: {\"name\":\"tool_name\",\"arguments\":{\"key\":\"value\"}}")
193	fmt.Println("  Commands: 'list' to show tools, 'quit' to exit")
194	fmt.Println()
195
196	scanner := bufio.NewScanner(os.Stdin)
197	for {
198		fmt.Print("> ")
199		if !scanner.Scan() {
200			break
201		}
202
203		input := strings.TrimSpace(scanner.Text())
204		if input == "" {
205			continue
206		}
207
208		if input == "quit" || input == "exit" {
209			break
210		}
211
212		if input == "list" {
213			fmt.Printf("Available tools (%d):\n", len(tools))
214			for _, tool := range tools {
215				fmt.Printf("  - %s: %s\n", tool.Name, tool.Description)
216				if len(tool.InputSchema) > 0 {
217					var schema map[string]interface{}
218					if err := json.Unmarshal(tool.InputSchema, &schema); err == nil {
219						schemaJSON, _ := json.MarshalIndent(schema, "    ", "  ")
220						fmt.Printf("    Schema: %s\n", string(schemaJSON))
221					}
222				}
223			}
224			fmt.Println()
225			continue
226		}
227
228		// Parse tool call - try function syntax first, then JSON
229		var toolName string
230		var toolArgs map[string]interface{}
231
232		if name, args, ok := parseFunctionCall(input); ok {
233			toolName = name
234			toolArgs = args
235		} else {
236			// Try JSON format
237			var toolCall struct {
238				Name      string                 `json:"name"`
239				Arguments map[string]interface{} `json:"arguments"`
240			}
241
242			if err := json.Unmarshal([]byte(input), &toolCall); err != nil {
243				fmt.Fprintf(os.Stderr, "Invalid syntax: %v\n", err)
244				fmt.Println("Expected: tool_name(args...) or {\"name\":\"tool_name\",\"arguments\":{...}}")
245				continue
246			}
247
248			toolName = toolCall.Name
249			toolArgs = toolCall.Arguments
250		}
251
252		if toolName == "" {
253			fmt.Fprintf(os.Stderr, "Tool name is required\n")
254			continue
255		}
256
257		// Call tool
258		fmt.Printf("Calling tool: %s\n", toolName)
259		if len(toolArgs) > 0 {
260			argsJSON, _ := json.MarshalIndent(toolArgs, "  ", "  ")
261			fmt.Printf("  Arguments: %s\n", string(argsJSON))
262		}
263		result, err := client.CallTool(ctx, toolName, toolArgs)
264		if err != nil {
265			fmt.Fprintf(os.Stderr, "Tool call failed: %v\n", err)
266			continue
267		}
268
269		// Print result
270		fmt.Println("Result:")
271		if result.IsError {
272			fmt.Println("  [ERROR]")
273		}
274		for _, content := range result.Content {
275			if content.Type == "text" {
276				fmt.Printf("  %s\n", content.Text)
277			} else {
278				fmt.Printf("  [%s content]\n", content.Type)
279			}
280		}
281		fmt.Println()
282	}
283
284	if err := scanner.Err(); err != nil {
285		fmt.Fprintf(os.Stderr, "Error reading input: %v\n", err)
286		os.Exit(1)
287	}
288
289	fmt.Println("Closing connection...")
290	client.Close()
291}