-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute.go
More file actions
213 lines (183 loc) · 6.25 KB
/
execute.go
File metadata and controls
213 lines (183 loc) · 6.25 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
package cobrax
import (
"bytes"
"context"
"fmt"
"log/slog"
"os"
"os/exec"
"github.com/mark3labs/mcp-go/mcp"
)
// executablePath holds the absolute path to the running binary. It is resolved
// once at startup and used by the subprocess-based [execute] function to
// re-invoke the same binary when serving tools through the legacy [Config] API.
var executablePath = initExecPath()
// initExecPath resolves the path of the currently running executable.
// It panics on error because a missing executable path means the process
// cannot re-invoke itself, which is a fatal misconfiguration.
func initExecPath() string {
path, err := os.Executable()
if err != nil {
panic(fmt.Sprintf("failed to get executable path: %v", err))
}
return path
}
// execute runs the CLI tool by re-invoking the current binary as a subprocess.
//
// This is the execution model used by the original [Config]-based API. The MCP
// server process re-launches itself with the decoded command arguments, captures
// stdout/stderr, and returns them in a [ToolOutput].
//
// Non-zero exit codes are surfaced in ToolOutput.ExitCode rather than as Go
// errors. A Go error is only returned if the subprocess cannot be launched at
// all (e.g. the binary is not found or lacks execute permission).
func execute(ctx context.Context, request mcp.CallToolRequest, input ToolInput) (*mcp.CallToolResult, ToolOutput, error) {
name := request.Params.Name
slog.Info("subprocess MCP tool request received", "tool", name)
// Build the argument slice from the tool name and input.
args := buildCommandArgs(name, input)
slog.Debug("executing subprocess command",
"tool", name,
"input", input,
"args", args,
)
// Launch the subprocess and capture its output.
var stdout, stderr bytes.Buffer
cmd := exec.CommandContext(ctx, executablePath, args...)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
exitCode := 0
err := cmd.Run()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
// The process ran but exited with a non-zero status; surface the
// exit code in the output rather than as a Go error.
exitCode = exitErr.ExitCode()
} else {
// A non-exit error means the subprocess could not start at all.
slog.Error("subprocess failed to launch", "tool", name, "error", err)
return nil, ToolOutput{}, err
}
}
return nil, ToolOutput{
StdOut: stdout.String(),
StdErr: stderr.String(),
ExitCode: exitCode,
}, nil
}
// splitToolName splits a tool name such as "myapp_sub_command" into its
// underscore-delimited segments: ["myapp", "sub", "command"].
// It is the inverse of the encoding performed by toolName in selector.go.
func splitToolName(name string) []string {
return splitOn(name, '_')
}
// splitOn splits s by the given separator rune.
func splitOn(s string, sep rune) []string {
var parts []string
start := 0
for i, r := range s {
if r == sep {
parts = append(parts, s[start:i])
start = i + 1
}
}
parts = append(parts, s[start:])
return parts
}
// buildCommandArgs constructs CLI arguments from the MCP request.
// It decodes the tool name back into a command path and appends flags and
// positional arguments so the resulting slice can be passed directly to
// exec.Command when re-invoking the binary as a subprocess.
//
// The flat ToolInput is split into flags (using FlagNames) and positional
// arguments (using ArgNames, which preserves cmd.Use ordering).
func buildCommandArgs(name string, input ToolInput) []string {
// Decode "root_sub_command" -> ["sub", "command"] by dropping the root prefix.
args := splitToolName(name)[1:]
// Split flat input into flags and positional args.
flagMap, posArgs := splitFlatInput(input)
// Add flags.
args = append(args, buildFlagArgs(flagMap)...)
// Add positional arguments in spec order.
return append(args, posArgs...)
}
// splitFlatInput separates a flat ToolInput into a flags map and an ordered
// positional-argument slice.
//
// Flags are identified by FlagNames; remaining entries in FlatInput that match
// ArgNames are collected in ArgNames order as positional arguments.
func splitFlatInput(input ToolInput) (flagMap map[string]any, posArgs []string) {
flagMap = make(map[string]any)
// Collect flag values.
for k, v := range input.FlatInput {
if _, isFlag := input.FlagNames[k]; isFlag {
flagMap[k] = v
}
}
// Collect positional args in the declared order.
for _, name := range input.ArgNames {
val, ok := input.FlatInput[name]
if !ok || val == nil {
continue
}
switch v := val.(type) {
case []any:
for _, item := range v {
posArgs = append(posArgs, fmt.Sprintf("%v", item))
}
case []string:
posArgs = append(posArgs, v...)
default:
posArgs = append(posArgs, fmt.Sprintf("%v", val))
}
}
return flagMap, posArgs
}
// buildFlagArgs converts a flags map into a slice of CLI flag arguments
// understood by cobra/pflag.
//
// Conversion rules:
// - bool true → "--flag" (false is omitted)
// - scalar → "--flag value"
// - []any → "--flag a" "--flag b" (repeated, one per element)
// - map[string]any → "--flag key=value" (stringToString style)
func buildFlagArgs(flagMap map[string]any) []string {
var args []string
for name, value := range flagMap {
if name == "" || value == nil {
continue
}
// Slice: emit one --flag per element (pflag slice / repeated flags).
if items, ok := value.([]any); ok {
for _, item := range items {
args = append(args, parseFlagArgValue(name, item)...)
}
continue
}
// Map: emit --flag key=value entries (pflag stringToString).
if mapVal, ok := value.(map[string]any); ok {
for k, v := range mapVal {
args = append(args, fmt.Sprintf("--%s", name), fmt.Sprintf("%s=%v", k, v))
}
continue
}
args = append(args, parseFlagArgValue(name, value)...)
}
return args
}
// parseFlagArgValue converts a single flag value to CLI argument tokens.
// A bool true yields ["--name"]; any other type yields ["--name", "value"].
// A bool false or nil value yields an empty slice (flag is omitted).
func parseFlagArgValue(name string, value any) (retVal []string) {
if value != nil {
switch v := value.(type) {
case bool:
if v {
retVal = append(retVal, fmt.Sprintf("--%s", name))
}
default:
retVal = append(retVal, fmt.Sprintf("--%s", name), fmt.Sprintf("%v", value))
}
}
return retVal
}