Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir>` answers `roots/list`.

```mermaid
flowchart LR
W["file change"] --> P["parse + generate + build"]
Expand All @@ -195,7 +199,7 @@ flowchart LR

### Flags and environment

`--tags/-t` forwards build tags. `serve`, `watch` and `stdio` also take `--dotenv/-e` (default `<module>/.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 `<module>/.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
Expand Down
8 changes: 8 additions & 0 deletions README_DEV.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
37 changes: 34 additions & 3 deletions cmd/gomcp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -61,23 +63,31 @@ 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
}
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),
Expand Down Expand Up @@ -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: <project_path>/.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."),
Expand Down
85 changes: 84 additions & 1 deletion cmd/gomcp/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,32 @@ 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 {
calls []string
build struct{ dir, out, tags string }
opts runner.Options
scaf scaffold.Options
req caller.Request
stdin string
err error
}

Expand All @@ -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),
}
}

Expand Down Expand Up @@ -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")
Expand Down
88 changes: 88 additions & 0 deletions cmd/gomcp/call.go
Original file line number Diff line number Diff line change
@@ -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 <project> [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
}
66 changes: 66 additions & 0 deletions e2e/call_test.go
Original file line number Diff line number Diff line change
@@ -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")
})
}
Loading
Loading