diff --git a/README.md b/README.md index 9e3bc0e..fbaefb0 100644 --- a/README.md +++ b/README.md @@ -183,9 +183,13 @@ gomcp build ./example ./bin/notes # one binary, contains both transports gomcp serve ./example # build + run over HTTP, Ctrl-C stops gracefully gomcp watch ./example # rebuild on change (HTTP only) gomcp stdio ./example # build + run over stdin and stdout +gomcp call ./example # list the tools +gomcp call ./example add_note '{"text":"hi"}' # call a tool, print the result gomcp version ``` +`call` tries a project without an AI client: it builds the project, starts it over stdio, lists the tools or calls one and stops the server. Text results go to stdout, build logs and errors to stderr. Arguments are a JSON object (`-` reads it from stdin), `--json` prints the raw result, and the exit code is 1 when the tool returns an error or the server a protocol error. Tools that ask the client for input (forms, sampling) are reported, not answered; `--root ` answers `roots/list`. + ```mermaid flowchart LR W["file change"] --> P["parse + generate + build"] @@ -195,7 +199,7 @@ flowchart LR ### Flags and environment -`--tags/-t` forwards build tags. `serve`, `watch` and `stdio` also take `--dotenv/-e` (default `/.env`; real environment wins). `serve` and `watch` take `--addr/-a` (sets `GOMCP_ADDR`, default `127.0.0.1:8080`, loopback only; set it to expose the server and configure `@MCP.Auth` first). +`--tags/-t` forwards build tags. `serve`, `watch`, `stdio` and `call` also take `--dotenv/-e` (default `/.env`; real environment wins). `serve` and `watch` take `--addr/-a` (sets `GOMCP_ADDR`, default `127.0.0.1:8080`, loopback only; set it to expose the server and configure `@MCP.Auth` first). ```sh gomcp serve ./example --addr 127.0.0.1:8765 --dotenv ./dev.env diff --git a/README_DEV.md b/README_DEV.md index 3df29c0..ba4a268 100644 --- a/README_DEV.md +++ b/README_DEV.md @@ -40,6 +40,14 @@ claude --mcp-config mcp.json Claude Code answers forms and URL pages itself in non-interactive runs, so use `e2e/` for exact checks of those paths. +## Quick manual test + +`gomcp call` builds the project and lists its tools or calls one, no AI client needed: +```sh +go run ./cmd/gomcp call ./example +go run ./cmd/gomcp call ./example add_note '{"text":"hi"}' +``` + ## Test stdio Over stdio the client starts the server itself, so build once and point the client at the binary: diff --git a/cmd/gomcp/app.go b/cmd/gomcp/app.go index 2e7bf97..c646b22 100644 --- a/cmd/gomcp/app.go +++ b/cmd/gomcp/app.go @@ -4,11 +4,13 @@ import ( "context" "fmt" "io" + "os" "regexp" "runtime/debug" "strings" "github.com/StevenCyb/GoCLI/pkg/cli" + "github.com/StevenCyb/GoMCP/internal/caller" "github.com/StevenCyb/GoMCP/internal/runner" "github.com/StevenCyb/GoMCP/internal/scaffold" ) @@ -61,15 +63,23 @@ type actions struct { serve func(ctx context.Context, o runner.Options) error watch func(ctx context.Context, o runner.Options) error init func(ctx context.Context, o scaffold.Options) error + call func(ctx context.Context, o runner.Options, req caller.Request, stdout io.Writer) error + stdin io.Reader // arguments of call given as "-" } func realActions() actions { - return actions{build: runner.Build, serve: runner.Serve, watch: runner.Watch, init: scaffold.Init} + return actions{build: runner.Build, serve: runner.Serve, watch: runner.Watch, init: scaffold.Init, call: caller.Run, stdin: os.Stdin} } // run executes the command line and returns the exit code. func run(ctx context.Context, args []string, stdout, stderr io.Writer, a actions) int { - app := newApp(ctx, stdout, stderr, a) + var call callInput + args, err := parseCall(args, &call) + if err != nil { + _, _ = fmt.Fprintln(stderr, err) + return 1 + } + app := newApp(ctx, stdout, stderr, a, &call) if _, err := app.RunWith(args); err != nil { _, _ = fmt.Fprintln(stderr, err) return 1 @@ -77,7 +87,7 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer, a actions return 0 } -func newApp(ctx context.Context, stdout, stderr io.Writer, a actions) *cli.CLI { +func newApp(ctx context.Context, stdout, stderr io.Writer, a actions, call *callInput) *cli.CLI { options := func(c *cli.Context) runner.Options { return runner.Options{ Dir: *c.GetArgument(argProject), @@ -145,6 +155,27 @@ func newApp(ctx context.Context, stdout, stderr io.Writer, a actions) *cli.CLI { }), ), ), + cli.Command( + "call", + cli.Description("Builds the project, lists its tools or calls one and prints the result, to try a tool without an AI client."), + cli.Argument( + argProject, + cli.Description("Path to the root of the Go project, then the tool name and its arguments as a JSON object (- reads stdin)."), + // parseCall reads the flags, they are declared for the help text + cli.Option(optJSON, cli.Description("Print the raw result as indented JSON.")), + cli.Option(optRoot, cli.Short('r'), cli.Description("Directory answered to roots/list, may be repeated.")), + cli.Option(optTags, cli.Short('t'), cli.Default(""), cli.Description("Build tags for go build.")), + cli.Option(optDotEnv, cli.Short('e'), cli.Default(""), + cli.Description("Path to a .env file for the server process (default: /.env).")), + cli.Handler(func(*cli.Context) error { + req, err := call.resolve(a.stdin) + if err != nil { + return err + } + return a.call(ctx, runner.Options{Dir: call.project, Tags: call.tags, DotEnv: call.dotenv, Stderr: stderr}, req, stdout) + }), + ), + ), cli.Command( "watch", cli.Description("Runs the project and restarts it on every change."), diff --git a/cmd/gomcp/app_test.go b/cmd/gomcp/app_test.go index 20f4f92..e3b478e 100644 --- a/cmd/gomcp/app_test.go +++ b/cmd/gomcp/app_test.go @@ -4,16 +4,23 @@ import ( "bytes" "context" "errors" + "io" "runtime/debug" + "strings" "testing" + "github.com/StevenCyb/GoMCP/internal/caller" "github.com/StevenCyb/GoMCP/internal/runner" "github.com/StevenCyb/GoMCP/internal/scaffold" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -const cmdServe = "serve" +const ( + cmdServe = "serve" + cmdCall = "call" + exampleDir = "./example" +) // fakeActions records the calls the CLI makes. type fakeActions struct { @@ -21,6 +28,8 @@ type fakeActions struct { build struct{ dir, out, tags string } opts runner.Options scaf scaffold.Options + req caller.Request + stdin string err error } @@ -46,6 +55,13 @@ func (f *fakeActions) actions() actions { f.opts = o return f.err }, + call: func(_ context.Context, o runner.Options, req caller.Request, stdout io.Writer) error { + f.calls = append(f.calls, "call") + f.opts, f.req = o, req + _, _ = io.WriteString(stdout, "result\n") + return f.err + }, + stdin: strings.NewReader(f.stdin), } } @@ -116,6 +132,73 @@ func TestStdioCommandHasNoAddressFlag(t *testing.T) { } } +func TestCallListsTools(t *testing.T) { + f := &fakeActions{} + code, stdout, stderr := execute(t, f, cmdCall, exampleDir) + require.Equal(t, 0, code, stderr) + assert.Equal(t, []string{cmdCall}, f.calls) + assert.Equal(t, "result\n", stdout, "the result is on stdout") + assert.Equal(t, exampleDir, f.opts.Dir) + assert.Empty(t, f.req.Tool, "no tool means listing") +} + +func TestCallATool(t *testing.T) { + f := &fakeActions{} + code, _, stderr := execute(t, f, cmdCall, exampleDir, "add_note", `{"text":"hi"}`) + require.Equal(t, 0, code, stderr) + assert.Equal(t, "add_note", f.req.Tool) + assert.JSONEq(t, `{"text":"hi"}`, string(f.req.Args)) + assert.False(t, f.req.JSON) +} + +func TestCallFlagsInAnyPosition(t *testing.T) { + f := &fakeActions{} + code, _, stderr := execute(t, f, cmdCall, "--json", "-t", "dev", exampleDir, "-e", "x.env", "get_note", "--root", "a", "-r", "b", `{"id":"1"}`) + require.Equal(t, 0, code, stderr) + assert.Equal(t, exampleDir, f.opts.Dir) + assert.Equal(t, "dev", f.opts.Tags) + assert.Equal(t, "x.env", f.opts.DotEnv) + assert.Equal(t, "get_note", f.req.Tool) + assert.True(t, f.req.JSON) + assert.Equal(t, []string{"a", "b"}, f.req.Roots) +} + +func TestCallArgumentsFromStdin(t *testing.T) { + f := &fakeActions{stdin: ` {"text":"from stdin"}` + "\n"} + code, _, stderr := execute(t, f, cmdCall, exampleDir, "add_note", "-") + require.Equal(t, 0, code, stderr) + assert.JSONEq(t, `{"text":"from stdin"}`, string(f.req.Args)) +} + +func TestCallRejectsBadInputBeforeBuilding(t *testing.T) { + cases := map[string][]string{ + "not json": {cmdCall, exampleDir, "add_note", "{text"}, + "not an object": {cmdCall, exampleDir, "add_note", "[1]"}, + "bad stdin": {cmdCall, exampleDir, "add_note", "-"}, + "unknown flag": {cmdCall, exampleDir, "--nope"}, + "missing value": {cmdCall, exampleDir, "--root"}, + "too many": {cmdCall, exampleDir, "add_note", "{}", "extra"}, + "no project": {cmdCall}, + } + for name, args := range cases { + t.Run(name, func(t *testing.T) { + f := &fakeActions{stdin: "nope"} + code, stdout, stderr := execute(t, f, args...) + assert.Equal(t, 1, code) + assert.NotEmpty(t, stderr) + assert.Empty(t, stdout) + assert.Empty(t, f.calls, "nothing is built") + }) + } +} + +func TestCallFailureExitsWithOneAndMessageOnStderr(t *testing.T) { + f := &fakeActions{err: &caller.ToolError{Message: "it broke"}} + code, _, stderr := execute(t, f, cmdCall, exampleDir, "fail") + assert.Equal(t, 1, code) + assert.Contains(t, stderr, "it broke") +} + func TestServeIsNotStdio(t *testing.T) { f := &fakeActions{} code, _, stderr := execute(t, f, cmdServe, "./example") diff --git a/cmd/gomcp/call.go b/cmd/gomcp/call.go new file mode 100644 index 0000000..576073f --- /dev/null +++ b/cmd/gomcp/call.go @@ -0,0 +1,88 @@ +package main + +import ( + "errors" + "fmt" + "io" + "strings" + + "github.com/StevenCyb/GoMCP/internal/caller" +) + +const optJSON, optRoot = "json", "root" + +// callInput is the command line of "gomcp call". The command line library takes the arguments in a +// fixed order and cannot make the tool and its arguments optional, so call parses its own line. +type callInput struct { + project, tool, args string + tags, dotenv string + roots []string + json bool +} + +// parseCall reads "gomcp call [tool [arguments]] [flags]" and returns the command line the +// command line library sees: the call command with only the project. A help flag or a missing project +// is left to the library. +func parseCall(args []string, in *callInput) ([]string, error) { + if len(args) < 2 || args[1] != "call" { + return args, nil + } + var positional []string + for i := 2; i < len(args); i++ { + a := args[i] + switch { + case a == "-h" || a == "--help": + return args, nil + case a == "--"+optJSON: + in.json = true + case a == "--"+optTags || a == "-t" || a == "--"+optDotEnv || a == "-e" || a == "--"+optRoot || a == "-r": + i++ + if i >= len(args) { + return nil, fmt.Errorf("%s needs a value", a) + } + switch a { + case "--" + optTags, "-t": + in.tags = args[i] + case "--" + optDotEnv, "-e": + in.dotenv = args[i] + default: + in.roots = append(in.roots, args[i]) + } + case strings.HasPrefix(a, "-") && a != "-": + return nil, fmt.Errorf("unknown flag %s", a) + default: + positional = append(positional, a) + } + } + if len(positional) == 0 { + return args[:2], nil // no project: the library reports the usage + } + if len(positional) > 3 { + return nil, errors.New("call takes a project path, a tool name and a JSON object") + } + in.project = positional[0] + if len(positional) > 1 { + in.tool = positional[1] + } + if len(positional) > 2 { + in.args = positional[2] + } + return []string{args[0], "call", in.project}, nil +} + +// resolve checks the arguments before anything is built: a JSON object, or "-" for stdin. +func (in *callInput) resolve(stdin io.Reader) (caller.Request, error) { + text := in.args + if text == "-" { + raw, err := io.ReadAll(stdin) + if err != nil { + return caller.Request{}, fmt.Errorf("read arguments from stdin: %w", err) + } + text = strings.TrimSpace(string(raw)) + } + parsed, err := caller.ParseArgs(text) + if err != nil { + return caller.Request{}, err + } + return caller.Request{Tool: in.tool, Args: parsed, JSON: in.json, Roots: in.roots}, nil +} diff --git a/e2e/call_test.go b/e2e/call_test.go new file mode 100644 index 0000000..f6ea3af --- /dev/null +++ b/e2e/call_test.go @@ -0,0 +1,66 @@ +package e2e_test + +// TestCall runs gomcp call against example/: it builds it and talks over the stdio pipes like the command does. + +import ( + "bytes" + "encoding/json" + "io" + "testing" + + "github.com/StevenCyb/GoMCP/internal/caller" + "github.com/StevenCyb/GoMCP/internal/runner" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const toolAdd = "add_note" + +func TestCall(t *testing.T) { + if testing.Short() { + t.Skip("builds and runs the example") + } + run := func(req caller.Request) (string, error) { + var out bytes.Buffer + err := caller.Run(t.Context(), runner.Options{Dir: "../example", Stderr: io.Discard}, req, &out) + return out.String(), err + } + + listing, err := run(caller.Request{}) + require.NoError(t, err) + assert.Regexp(t, `(?m)^add_note +\S`, listing) + assert.Contains(t, listing, "required: text") + + added, err := run(caller.Request{Tool: toolAdd, Args: json.RawMessage(`{"text":"from call"}`)}) + require.NoError(t, err) + assert.Contains(t, added, "from call") + + // every call starts its own server: the notes of the first are gone, so the failing call is a real one + _, err = run(caller.Request{Tool: "get_note", Args: json.RawMessage(`{"id":"missing"}`)}) + var toolErr *caller.ToolError + require.ErrorAs(t, err, &toolErr, "a failing tool is exit code 1 in the command") + assert.NotEmpty(t, toolErr.Message) + + raw, err := run(caller.Request{Tool: toolAdd, Args: json.RawMessage(`{"text":"json"}`), JSON: true}) + require.NoError(t, err) + assert.Regexp(t, `(?s)^\{\n .*"content"`, raw) + + var rpcErr *caller.RPCError + _, err = run(caller.Request{Tool: "no_such_tool"}) + require.ErrorAs(t, err, &rpcErr) + + t.Run("a tool that asks the client for input", func(t *testing.T) { + var inputErr *caller.InputError + _, err := run(caller.Request{Tool: "delete_note", Args: json.RawMessage(`{"id":"1"}`)}) + require.ErrorAs(t, err, &inputErr) + assert.Contains(t, err.Error(), "elicitation") + + _, err = run(caller.Request{Tool: toolImport}) + require.ErrorAs(t, err, &inputErr) + assert.Contains(t, err.Error(), "--root") + + done, err := run(caller.Request{Tool: toolImport, Roots: []string{t.TempDir()}}) + require.NoError(t, err, "roots are answered with --root") + assert.Contains(t, done, "1") + }) +} diff --git a/internal/caller/caller.go b/internal/caller/caller.go new file mode 100644 index 0000000..6658fe6 --- /dev/null +++ b/internal/caller/caller.go @@ -0,0 +1,277 @@ +// Package caller is a tiny MCP client for the terminal: it lists the tools of a stdio server and calls +// one, so a project can be tried without an AI client. +package caller + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "maps" + "net/url" + "path/filepath" + "slices" + "strconv" + "strings" +) + +const ( + specVersion = "2026-07-28" + metaVersion = "io.modelcontextprotocol/protocolVersion" + metaCaps = "io.modelcontextprotocol/clientCapabilities" + maxRounds = 8 // input_required retries before giving up +) + +// RPCError is a JSON-RPC error of the server. +type RPCError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func (e *RPCError) Error() string { return fmt.Sprintf("error %d: %s", e.Code, e.Message) } + +// ToolError is a tool that ran and reported isError. +type ToolError struct{ Message string } + +func (e *ToolError) Error() string { return "tool error: " + e.Message } + +// InputError is a tool that needs something from the client that this client cannot give. +type InputError struct{ Needs []string } + +func (e *InputError) Error() string { + return "the tool needs input from the client (" + strings.Join(e.Needs, "; ") + "), which gomcp call cannot answer" +} + +// Tool is a tool as listed by the server. +type Tool struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema struct { + Properties map[string]json.RawMessage `json:"properties"` + Required []string `json:"required"` + } `json:"inputSchema"` +} + +// Client speaks the stateless protocol over a stdio pipe pair. +type Client struct { + w io.Writer + sc *bufio.Scanner + id int + roots []string // directories answered to roots/list +} + +// New returns a client that writes requests to w and reads responses from r. roots are the directories +// it answers to roots/list. +func New(w io.Writer, r io.Reader, roots []string) *Client { + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 0, 64*1024), 16<<20) + return &Client{w: w, sc: sc, roots: roots} +} + +type message struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Result json.RawMessage `json:"result"` + Error *RPCError `json:"error"` +} + +// request sends one request and returns its result; notifications in between are skipped. +func (c *Client) request(method string, params map[string]any) (json.RawMessage, error) { + c.id++ + // the client declares what it could answer, so that tools reach the point of asking and gomcp call can say what they need + meta := map[string]any{metaVersion: specVersion, metaCaps: map[string]any{ + "roots": map[string]any{}, "sampling": map[string]any{}, "elicitation": map[string]any{"form": map[string]any{}, "url": map[string]any{}}, + }} + p := map[string]any{"_meta": meta} + maps.Copy(p, params) + raw, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": c.id, "method": method, "params": p}) + if err != nil { + return nil, fmt.Errorf("encode request: %w", err) + } + if _, err := c.w.Write(append(raw, '\n')); err != nil { + return nil, fmt.Errorf("send request: %w", err) + } + want := []byte(strconv.Itoa(c.id)) + for c.sc.Scan() { + var m message + if err := json.Unmarshal(c.sc.Bytes(), &m); err != nil { + return nil, fmt.Errorf("server sent something that is not JSON: %w", err) + } + if m.Method != "" || !bytes.Equal(m.ID, want) { + continue + } + if m.Error != nil { + return nil, m.Error + } + return m.Result, nil + } + if err := c.sc.Err(); err != nil { + return nil, fmt.Errorf("read response: %w", err) + } + return nil, errors.New("the server closed the connection") +} + +// Tools lists all tools, following the pages. +func (c *Client) Tools() ([]Tool, error) { + var all []Tool + params := map[string]any{} + for range 1000 { + raw, err := c.request("tools/list", params) + if err != nil { + return nil, err + } + var page struct { + Tools []Tool `json:"tools"` + NextCursor string `json:"nextCursor"` + } + if err := json.Unmarshal(raw, &page); err != nil { + return nil, fmt.Errorf("decode tools/list: %w", err) + } + all = append(all, page.Tools...) + if page.NextCursor == "" { + return all, nil + } + params = map[string]any{"cursor": page.NextCursor} + } + return nil, errors.New("tools/list does not end") +} + +type inputRequired struct { + ResultType string `json:"resultType"` + InputRequests map[string]struct { + Method string `json:"method"` + Params struct { + Message string `json:"message"` + } `json:"params"` + } `json:"inputRequests"` + RequestState string `json:"requestState"` +} + +// Call calls a tool and returns the raw result. A result with isError is returned together with a *ToolError. +func (c *Client) Call(name string, args json.RawMessage) (json.RawMessage, error) { + var arguments any = map[string]any{} + if len(args) > 0 { + arguments = args + } + params := map[string]any{"name": name, "arguments": arguments} + for range maxRounds { + raw, err := c.request("tools/call", params) + if err != nil { + return nil, err + } + var in inputRequired + if json.Unmarshal(raw, &in) != nil || in.ResultType != "input_required" { + return raw, toolError(raw) + } + answers := map[string]any{} + var needs []string + for key, r := range in.InputRequests { + switch { + case r.Method == "roots/list" && len(c.roots) > 0: + answers[key] = map[string]any{"roots": c.rootList()} + case r.Method == "roots/list": + needs = append(needs, "roots, pass --root ") + case r.Method == "elicitation/create": + needs = append(needs, "elicitation: "+r.Params.Message) + case r.Method == "sampling/createMessage": + needs = append(needs, "sampling") + default: + needs = append(needs, r.Method) + } + } + if len(needs) > 0 { + slices.Sort(needs) + return nil, &InputError{Needs: needs} + } + params = map[string]any{"name": name, "arguments": arguments, "inputResponses": answers} + if in.RequestState != "" { + params["requestState"] = in.RequestState + } + } + return nil, errors.New("the tool keeps asking for input") +} + +func (c *Client) rootList() []map[string]string { + out := make([]map[string]string, 0, len(c.roots)) + for _, dir := range c.roots { + abs, err := filepath.Abs(dir) + if err != nil { + abs = dir + } + p := filepath.ToSlash(abs) + if !strings.HasPrefix(p, "/") { // C:/dir becomes /C:/dir + p = "/" + p + } + out = append(out, map[string]string{"uri": (&url.URL{Scheme: "file", Path: p}).String()}) + } + return out +} + +type toolResult struct { + IsError bool `json:"isError"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` +} + +// Text returns the text content blocks of a tool result, one per line. +func Text(raw json.RawMessage) string { + var r toolResult + _ = json.Unmarshal(raw, &r) + var lines []string + for _, b := range r.Content { + if b.Type == "text" { + lines = append(lines, b.Text) + } + } + return strings.Join(lines, "\n") +} + +func toolError(raw json.RawMessage) error { + var r toolResult + if json.Unmarshal(raw, &r) == nil && r.IsError { + return &ToolError{Message: Text(raw)} + } + return nil +} + +// Indent pretty-prints raw JSON. +func Indent(raw json.RawMessage) string { + var b bytes.Buffer + if json.Indent(&b, raw, "", " ") != nil { + return string(raw) + } + return b.String() +} + +// FormatTools renders the tools as a table of name and first description line, followed by the input +// properties of each tool. +func FormatTools(tools []Tool) string { + width := 0 + for _, t := range tools { + width = max(width, len(t.Name)) + } + var b strings.Builder + for _, t := range tools { + first, _, _ := strings.Cut(strings.TrimSpace(t.Description), "\n") + fmt.Fprintf(&b, "%-*s %s\n", width, t.Name, first) + required := t.InputSchema.Required + var optional []string + for name := range t.InputSchema.Properties { + if !slices.Contains(required, name) { + optional = append(optional, name) + } + } + slices.Sort(optional) + if len(required) > 0 { + fmt.Fprintf(&b, " required: %s\n", strings.Join(required, ", ")) + } + if len(optional) > 0 { + fmt.Fprintf(&b, " optional: %s\n", strings.Join(optional, ", ")) + } + } + return b.String() +} diff --git a/internal/caller/caller_test.go b/internal/caller/caller_test.go new file mode 100644 index 0000000..70e5a1e --- /dev/null +++ b/internal/caller/caller_test.go @@ -0,0 +1,135 @@ +package caller_test + +import ( + "context" + "encoding/json" + "io" + "strings" + "testing" + + "github.com/StevenCyb/GoMCP/internal/caller" + "github.com/StevenCyb/GoMCP/pkg/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type textIn struct { + Text string `json:"text"` + Tag string `json:"tag,omitempty"` +} + +type confirm struct { + OK bool `desc:"Really?" json:"ok"` +} + +func newServer(t *testing.T) *mcp.Server { + t.Helper() + s := mcp.NewServer(mcp.Info{Name: "fake", Version: "1"}, mcp.WithPageSize(2)) + require.NoError(t, mcp.AddTool(s, mcp.ToolDef{Name: "echo", Description: "Echoes the text.\nSecond line."}, + func(_ mcp.Context, in textIn) (string, error) { return "echo " + in.Text, nil })) + require.NoError(t, mcp.AddTool(s, mcp.ToolDef{Name: "fail"}, + func(_ mcp.Context, _ mcp.Empty) (string, error) { return "", mcp.ToolError("it broke") })) + require.NoError(t, mcp.AddTool(s, mcp.ToolDef{Name: "ask", Requires: []string{mcp.CapElicitation}}, + func(ctx mcp.Context, _ mcp.Empty) (string, error) { + _, _, err := mcp.Elicit[confirm](ctx, "Delete it?") + return "done", err + })) + require.NoError(t, mcp.AddTool(s, mcp.ToolDef{Name: "where", Requires: []string{mcp.CapRoots}}, + func(ctx mcp.Context, _ mcp.Empty) (string, error) { + roots, err := ctx.Roots() + if err != nil || len(roots) == 0 { + return "", err + } + return roots[0].URI, nil + })) + return s +} + +func client(t *testing.T, roots ...string) *caller.Client { + t.Helper() + inR, inW := io.Pipe() + outR, outW := io.Pipe() + s := newServer(t) + go func() { + _ = s.ServeStdio(context.Background(), inR, outW) + _ = outW.Close() + }() + t.Cleanup(func() { _ = inW.Close() }) + return caller.New(inW, outR, roots) +} + +func TestToolsFollowsPagesAndFormats(t *testing.T) { + tools, err := client(t).Tools() + require.NoError(t, err) + require.Len(t, tools, 4, "page size 2 means two pages") + + out := caller.FormatTools(tools) + assert.Contains(t, out, "echo Echoes the text.\n") + assert.NotContains(t, out, "Second line") + assert.Contains(t, out, "required: text") + assert.Contains(t, out, "optional: tag") +} + +func TestCallText(t *testing.T) { + raw, err := client(t).Call("echo", json.RawMessage(`{"text":"hi"}`)) + require.NoError(t, err) + assert.Equal(t, "echo hi", caller.Text(raw)) + assert.Contains(t, caller.Indent(raw), "\n \"content\"") +} + +func TestCallToolError(t *testing.T) { + raw, err := client(t).Call("fail", nil) + var toolErr *caller.ToolError + require.ErrorAs(t, err, &toolErr) + assert.Equal(t, "it broke", toolErr.Message) + assert.NotNil(t, raw) +} + +func TestCallProtocolError(t *testing.T) { + _, err := client(t).Call("nope", nil) + var rpcErr *caller.RPCError + require.ErrorAs(t, err, &rpcErr) + assert.NotZero(t, rpcErr.Code) + assert.Contains(t, err.Error(), rpcErr.Message) +} + +func TestCallInputRequiredIsNamed(t *testing.T) { + _, err := client(t).Call("ask", nil) + var inputErr *caller.InputError + require.ErrorAs(t, err, &inputErr) + assert.Contains(t, err.Error(), "elicitation: Delete it?") + + _, err = client(t).Call("where", nil) + require.ErrorAs(t, err, &inputErr) + assert.Contains(t, err.Error(), "--root") +} + +func TestCallAnswersRoots(t *testing.T) { + raw, err := client(t, t.TempDir()).Call("where", nil) + require.NoError(t, err) + assert.True(t, strings.HasPrefix(caller.Text(raw), "file:///"), caller.Text(raw)) +} + +func TestParseArgs(t *testing.T) { + got, err := caller.ParseArgs(`{"a":1}`) + require.NoError(t, err) + assert.JSONEq(t, `{"a":1}`, string(got)) + + got, err = caller.ParseArgs("") + require.NoError(t, err) + assert.Empty(t, got) + + for _, bad := range []string{"{", "[1]", "null", `"x"`, "5"} { + _, err = caller.ParseArgs(bad) + require.Error(t, err, bad) + } +} + +func TestClosedServer(t *testing.T) { + inR, inW := io.Pipe() + outR, outW := io.Pipe() + _ = inR.Close() + _ = outW.Close() + _, err := caller.New(inW, outR, nil).Tools() + require.Error(t, err) +} diff --git a/internal/caller/run.go b/internal/caller/run.go new file mode 100644 index 0000000..947041e --- /dev/null +++ b/internal/caller/run.go @@ -0,0 +1,81 @@ +package caller + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + + "github.com/StevenCyb/GoMCP/internal/runner" +) + +// Request is what Run does: list the tools when Tool is empty, otherwise call it. +type Request struct { + Tool string + Args json.RawMessage // JSON object, empty for none + JSON bool // print the raw result as indented JSON instead of the text + Roots []string // directories answered to roots/list +} + +// ParseArgs checks that args is empty or a JSON object. +func ParseArgs(args string) (json.RawMessage, error) { + if args == "" { + return nil, nil + } + var obj map[string]any + if err := json.Unmarshal([]byte(args), &obj); err != nil || obj == nil { + return nil, errors.New("the arguments must be a JSON object, for example '{\"text\":\"hi\"}'") + } + return json.RawMessage(args), nil +} + +// Run builds the project, starts it over stdio, performs the request, prints the outcome to stdout and +// ends the server by closing its stdin. o.Stdout and o.Stdin are replaced, o.Stderr gets the logs. +func Run(ctx context.Context, o runner.Options, req Request, stdout io.Writer) error { + inR, inW := io.Pipe() + outR, outW := io.Pipe() + o.Stdio, o.Stdin, o.Stdout = true, inR, outW + done := make(chan error, 1) + go func() { + err := runner.Serve(ctx, o) + _ = outW.Close() + _ = inR.Close() + done <- err + }() + + err := talk(New(inW, outR, req.Roots), req, stdout) + _ = inW.Close() // end of input stops the server + _ = outR.Close() + if serr := <-done; serr != nil { + var rpc *RPCError + var tool *ToolError + var input *InputError + if !errors.As(err, &rpc) && !errors.As(err, &tool) && !errors.As(err, &input) { + err = serr // the server did not start or died: that is the cause of any pipe error + } + } + return err +} + +func talk(c *Client, req Request, stdout io.Writer) error { + if req.Tool == "" { + tools, err := c.Tools() + if err != nil { + return err + } + _, err = io.WriteString(stdout, FormatTools(tools)) + return err + } + raw, err := c.Call(req.Tool, req.Args) + if raw != nil && (req.JSON || err == nil) { // a tool error is printed once, by the caller of Run + out := Text(raw) + if req.JSON { + out = Indent(raw) + } + if _, werr := fmt.Fprintln(stdout, out); werr != nil { + return werr + } + } + return err +}