From 72dee23167dc8245d2fdf77acdf8af33d7f1ceec Mon Sep 17 00:00:00 2001 From: StevenCyb <41087154+StevenCyb@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:30:34 +0100 Subject: [PATCH 1/5] refactor: move example to examples/features Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/test.yml | 5 ++-- cmd/gomcp/app_test.go | 26 +++++++++---------- e2e/features_test.go | 4 +-- {example => examples/features}/README.md | 8 +++--- {example => examples/features}/assets/add.svg | 0 .../features}/assets/notes.svg | 0 {example => examples/features}/auth.go | 0 {example => examples/features}/elicitation.go | 0 {example => examples/features}/go.mod | 2 +- {example => examples/features}/lifecycle.go | 0 {example => examples/features}/middleware.go | 0 {example => examples/features}/model.go | 0 .../features}/prompts_completion.go | 0 {example => examples/features}/resources.go | 0 {example => examples/features}/sampling.go | 0 .../features}/server_transport.go | 0 .../features}/static_assets.go | 0 {example => examples/features}/task_import.go | 0 {example => examples/features}/tools.go | 0 internal/parser/parser_test.go | 2 +- 20 files changed, 23 insertions(+), 24 deletions(-) rename {example => examples/features}/README.md (84%) rename {example => examples/features}/assets/add.svg (100%) rename {example => examples/features}/assets/notes.svg (100%) rename {example => examples/features}/auth.go (100%) rename {example => examples/features}/elicitation.go (100%) rename {example => examples/features}/go.mod (68%) rename {example => examples/features}/lifecycle.go (100%) rename {example => examples/features}/middleware.go (100%) rename {example => examples/features}/model.go (100%) rename {example => examples/features}/prompts_completion.go (100%) rename {example => examples/features}/resources.go (100%) rename {example => examples/features}/sampling.go (100%) rename {example => examples/features}/server_transport.go (100%) rename {example => examples/features}/static_assets.go (100%) rename {example => examples/features}/task_import.go (100%) rename {example => examples/features}/tools.go (100%) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 77fc3e0..e76bf3a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,9 +23,8 @@ jobs: # the runner tests build and run generated servers, so they need a few minutes - run: go test -race -timeout 5m ./... - # example is its own module; it must keep compiling against the runtime - - run: go vet ./... - working-directory: example + # every example is its own module; it must keep compiling against the runtime and pass its own tests + - run: for d in examples/*/; do (cd "$d" && go vet ./... && go test ./...) || exit 1; done # Windows is a release target. This job is informative and not a required check: # it shows early when a change breaks the build or the tests there. diff --git a/cmd/gomcp/app_test.go b/cmd/gomcp/app_test.go index e3b478e..0735282 100644 --- a/cmd/gomcp/app_test.go +++ b/cmd/gomcp/app_test.go @@ -82,10 +82,10 @@ func TestVersion(t *testing.T) { func TestBuild(t *testing.T) { f := &fakeActions{} - code, _, stderr := execute(t, f, "build", "./example", "./bin/notes") + code, _, stderr := execute(t, f, "build", "./examples/features", "./bin/notes") require.Equal(t, 0, code, stderr) assert.Equal(t, []string{"build"}, f.calls) - assert.Equal(t, "./example", f.build.dir) + assert.Equal(t, "./examples/features", f.build.dir) assert.Equal(t, "./bin/notes", f.build.out) assert.Empty(t, f.build.tags) } @@ -93,7 +93,7 @@ func TestBuild(t *testing.T) { func TestBuildWithTags(t *testing.T) { for _, flag := range []string{"--tags", "-t"} { f := &fakeActions{} - code, _, stderr := execute(t, f, "build", "./example", "./out", flag, "integration") + code, _, stderr := execute(t, f, "build", "./examples/features", "./out", flag, "integration") require.Equal(t, 0, code, stderr) assert.Equal(t, "integration", f.build.tags, flag) } @@ -101,10 +101,10 @@ func TestBuildWithTags(t *testing.T) { func TestServe(t *testing.T) { f := &fakeActions{} - code, _, stderr := execute(t, f, cmdServe, "./example") + code, _, stderr := execute(t, f, cmdServe, "./examples/features") require.Equal(t, 0, code, stderr) assert.Equal(t, []string{cmdServe}, f.calls) - assert.Equal(t, "./example", f.opts.Dir) + assert.Equal(t, "./examples/features", f.opts.Dir) assert.Empty(t, f.opts.Tags) assert.Empty(t, f.opts.DotEnv) assert.Empty(t, f.opts.Addr) @@ -112,11 +112,11 @@ func TestServe(t *testing.T) { func TestStdioCommand(t *testing.T) { f := &fakeActions{} - code, _, stderr := execute(t, f, "stdio", "./example", "--tags", "dev", "--dotenv", "x.env") + code, _, stderr := execute(t, f, "stdio", "./examples/features", "--tags", "dev", "--dotenv", "x.env") require.Equal(t, 0, code, stderr) assert.Equal(t, []string{cmdServe}, f.calls, "stdio runs the server like serve does, over stdin and stdout") assert.True(t, f.opts.Stdio) - assert.Equal(t, "./example", f.opts.Dir) + assert.Equal(t, "./examples/features", f.opts.Dir) assert.Equal(t, "dev", f.opts.Tags) assert.Equal(t, "x.env", f.opts.DotEnv) assert.Empty(t, f.opts.Addr, "there is no listen address over stdio") @@ -124,7 +124,7 @@ func TestStdioCommand(t *testing.T) { func TestStdioCommandHasNoAddressFlag(t *testing.T) { f := &fakeActions{} - code, _, stderr := execute(t, f, "stdio", "./example", "--addr", ":1") + code, _, stderr := execute(t, f, "stdio", "./examples/features", "--addr", ":1") if code == 0 { // the command line library may ignore unknown flags assert.Empty(t, f.opts.Addr) } else { @@ -201,7 +201,7 @@ func TestCallFailureExitsWithOneAndMessageOnStderr(t *testing.T) { func TestServeIsNotStdio(t *testing.T) { f := &fakeActions{} - code, _, stderr := execute(t, f, cmdServe, "./example") + code, _, stderr := execute(t, f, cmdServe, "./examples/features") require.Equal(t, 0, code, stderr) assert.False(t, f.opts.Stdio) } @@ -210,7 +210,7 @@ func TestServeAndWatchFlags(t *testing.T) { for _, command := range []string{cmdServe, "watch"} { t.Run(command, func(t *testing.T) { f := &fakeActions{} - code, _, stderr := execute(t, f, command, "./example", "-t", "dev", "-e", "local.env", "-a", ":9000") + code, _, stderr := execute(t, f, command, "./examples/features", "-t", "dev", "-e", "local.env", "-a", ":9000") require.Equal(t, 0, code, stderr) assert.Equal(t, []string{command}, f.calls) assert.Equal(t, "dev", f.opts.Tags) @@ -218,7 +218,7 @@ func TestServeAndWatchFlags(t *testing.T) { assert.Equal(t, ":9000", f.opts.Addr) f = &fakeActions{} - code, _, stderr = execute(t, f, command, "./example", "--tags", "dev", "--dotenv", "local.env", "--addr", ":9001") + code, _, stderr = execute(t, f, command, "./examples/features", "--tags", "dev", "--dotenv", "local.env", "--addr", ":9001") require.Equal(t, 0, code, stderr) assert.Equal(t, ":9001", f.opts.Addr) assert.Equal(t, "local.env", f.opts.DotEnv) @@ -229,7 +229,7 @@ func TestServeAndWatchFlags(t *testing.T) { func TestOutputStreamsAreForwarded(t *testing.T) { f := &fakeActions{} var stdout, stderr bytes.Buffer - code := run(t.Context(), []string{"gomcp", cmdServe, "./example"}, &stdout, &stderr, f.actions()) + code := run(t.Context(), []string{"gomcp", cmdServe, "./examples/features"}, &stdout, &stderr, f.actions()) require.Equal(t, 0, code) assert.Same(t, &stdout, f.opts.Stdout) assert.Same(t, &stderr, f.opts.Stderr) @@ -248,7 +248,7 @@ func TestUsageErrors(t *testing.T) { cases := map[string][]string{ "unknown command": {"deploy"}, "no command": {}, - "build needs paths": {"build", "./example"}, + "build needs paths": {"build", "./examples/features"}, "serve needs path": {cmdServe}, } for name, args := range cases { diff --git a/e2e/features_test.go b/e2e/features_test.go index 5f45592..8d52065 100644 --- a/e2e/features_test.go +++ b/e2e/features_test.go @@ -1,4 +1,4 @@ -// Feature tests: build and run example/, then check every feature of it through the test client. +// Feature tests: build and run examples/features/, then check every feature of it through the test client. package e2e_test @@ -38,7 +38,7 @@ func startExample(t *testing.T) string { ctx, cancel := context.WithCancel(t.Context()) done := make(chan error, 1) go func() { - done <- runner.Serve(ctx, runner.Options{Dir: "../example", Stdout: io.Discard, Stderr: io.Discard}) + done <- runner.Serve(ctx, runner.Options{Dir: "../examples/features", Stdout: io.Discard, Stderr: io.Discard}) }() t.Cleanup(func() { cancel() diff --git a/example/README.md b/examples/features/README.md similarity index 84% rename from example/README.md rename to examples/features/README.md index 36c0118..eab6d73 100644 --- a/example/README.md +++ b/examples/features/README.md @@ -1,17 +1,17 @@ -# Example +# Features example A notes server that uses every GoMCP feature once. The annotations are the documentation: read a file next to the README section named below. ```sh -gomcp serve ./example # MCP endpoint on http://127.0.0.1:8080/mcp -gomcp stdio ./example # the same server over stdin and stdout, for a client that starts it +gomcp serve ./examples/features # MCP endpoint on http://127.0.0.1:8080/mcp +gomcp stdio ./examples/features # the same server over stdin and stdout, for a client that starts it ``` Over stdio there is no authentication (see "Local or remote" in the main README). The OAuth verifier in `auth.go` is a **stub**: it accepts any non-empty bearer -token. Never use it as it is. `e2e/` builds and runs this example and checks +token. Never use it as it is. `e2e/` builds and runs it and checks every feature through a test client, so it stays working. | File | Shows | README section | diff --git a/example/assets/add.svg b/examples/features/assets/add.svg similarity index 100% rename from example/assets/add.svg rename to examples/features/assets/add.svg diff --git a/example/assets/notes.svg b/examples/features/assets/notes.svg similarity index 100% rename from example/assets/notes.svg rename to examples/features/assets/notes.svg diff --git a/example/auth.go b/examples/features/auth.go similarity index 100% rename from example/auth.go rename to examples/features/auth.go diff --git a/example/elicitation.go b/examples/features/elicitation.go similarity index 100% rename from example/elicitation.go rename to examples/features/elicitation.go diff --git a/example/go.mod b/examples/features/go.mod similarity index 68% rename from example/go.mod rename to examples/features/go.mod index 9087c33..44458b0 100644 --- a/example/go.mod +++ b/examples/features/go.mod @@ -4,4 +4,4 @@ go 1.26.2 require github.com/StevenCyb/GoMCP v0.0.0 -replace github.com/StevenCyb/GoMCP => ../ +replace github.com/StevenCyb/GoMCP => ../.. diff --git a/example/lifecycle.go b/examples/features/lifecycle.go similarity index 100% rename from example/lifecycle.go rename to examples/features/lifecycle.go diff --git a/example/middleware.go b/examples/features/middleware.go similarity index 100% rename from example/middleware.go rename to examples/features/middleware.go diff --git a/example/model.go b/examples/features/model.go similarity index 100% rename from example/model.go rename to examples/features/model.go diff --git a/example/prompts_completion.go b/examples/features/prompts_completion.go similarity index 100% rename from example/prompts_completion.go rename to examples/features/prompts_completion.go diff --git a/example/resources.go b/examples/features/resources.go similarity index 100% rename from example/resources.go rename to examples/features/resources.go diff --git a/example/sampling.go b/examples/features/sampling.go similarity index 100% rename from example/sampling.go rename to examples/features/sampling.go diff --git a/example/server_transport.go b/examples/features/server_transport.go similarity index 100% rename from example/server_transport.go rename to examples/features/server_transport.go diff --git a/example/static_assets.go b/examples/features/static_assets.go similarity index 100% rename from example/static_assets.go rename to examples/features/static_assets.go diff --git a/example/task_import.go b/examples/features/task_import.go similarity index 100% rename from example/task_import.go rename to examples/features/task_import.go diff --git a/example/tools.go b/examples/features/tools.go similarity index 100% rename from example/tools.go rename to examples/features/tools.go diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index 0eb459c..28587d7 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -49,7 +49,7 @@ func parseErr(t *testing.T, files map[string]string) string { const header = "package api\n\nimport (\n\t\"context\"\n\t\"github.com/StevenCyb/GoMCP/pkg/mcp\"\n)\n\nvar _ context.Context\n\n" func TestParseExampleDirectory(t *testing.T) { - p, err := parser.Parse("../../example") + p, err := parser.Parse("../../examples/features") require.NoError(t, err) assert.Equal(t, "github.com/StevenCyb/example_mcp", p.Module.Path) From c85bd84c0ff8395424e24314b2c17dc4641e9384 Mon Sep 17 00:00:00 2001 From: StevenCyb <41087154+StevenCyb@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:30:35 +0100 Subject: [PATCH 2/5] feat: add hello, files, todo and fetch examples Co-Authored-By: Claude Sonnet 5.5 --- examples/fetch/README.md | 25 ++++++ examples/fetch/fetch.go | 107 +++++++++++++++++++++++++ examples/fetch/fetch_test.go | 54 +++++++++++++ examples/fetch/go.mod | 7 ++ examples/files/README.md | 28 +++++++ examples/files/files.go | 123 +++++++++++++++++++++++++++++ examples/files/files_test.go | 49 ++++++++++++ examples/files/go.mod | 7 ++ examples/hello/README.md | 18 +++++ examples/hello/go.mod | 7 ++ examples/hello/hello.go | 15 ++++ examples/todo/README.md | 29 +++++++ examples/todo/go.mod | 7 ++ examples/todo/todo.go | 147 +++++++++++++++++++++++++++++++++++ examples/todo/todo_test.go | 39 ++++++++++ 15 files changed, 662 insertions(+) create mode 100644 examples/fetch/README.md create mode 100644 examples/fetch/fetch.go create mode 100644 examples/fetch/fetch_test.go create mode 100644 examples/fetch/go.mod create mode 100644 examples/files/README.md create mode 100644 examples/files/files.go create mode 100644 examples/files/files_test.go create mode 100644 examples/files/go.mod create mode 100644 examples/hello/README.md create mode 100644 examples/hello/go.mod create mode 100644 examples/hello/hello.go create mode 100644 examples/todo/README.md create mode 100644 examples/todo/go.mod create mode 100644 examples/todo/todo.go create mode 100644 examples/todo/todo_test.go diff --git a/examples/fetch/README.md b/examples/fetch/README.md new file mode 100644 index 0000000..9ad5cc5 --- /dev/null +++ b/examples/fetch/README.md @@ -0,0 +1,25 @@ +# fetch + +Tool `fetch_url`: GET a page and return it as text. + +- Only `http` and `https`, only hosts in `FETCH_ALLOW` (comma separated). **Empty denies everything**, and the error says so. +- 10 second timeout, at most 256 KiB of body (the result says `truncated`), redirects are checked against the allowlist again. +- Failures are `mcp.ToolError`s, so the model sees the reason. No client feature is required, so HTTP and stdio both work. + +```sh +FETCH_ALLOW=example.com,go.dev gomcp serve ./examples/fetch +``` + +Client config for stdio (build once, `gomcp stdio` compiles on every start): + +```sh +gomcp build ./examples/fetch ./bin/fetch +``` + +```json +{ + "mcpServers": { + "fetch": { "command": "/absolute/path/to/bin/fetch", "args": ["--stdio"], "env": { "FETCH_ALLOW": "example.com,go.dev" } } + } +} +``` diff --git a/examples/fetch/fetch.go b/examples/fetch/fetch.go new file mode 100644 index 0000000..10f7dc1 --- /dev/null +++ b/examples/fetch/fetch.go @@ -0,0 +1,107 @@ +// Example: fetch a web page as text, with limits. Only hosts in FETCH_ALLOW (comma +// separated) can be reached; an empty list denies everything. The tool needs no +// client features (no Requires), so it works over HTTP and stdio alike. + +// @MCP.Server("fetch", version="1.0.0") +// @MCP.Instructions("fetch_url downloads a page with GET. Only hosts the operator allowed can be fetched.") +package api + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/StevenCyb/GoMCP/pkg/mcp" +) + +const ( + maxBody = 256 << 10 // bytes read from a response + timeout = 10 * time.Second +) + +// check validates the URL against the allowlist and returns it parsed. +func check(raw string, allow []string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" { + return nil, errors.New("only absolute http and https URLs are allowed") + } + if len(allow) == 0 { + return nil, errors.New("no host is allowed: set FETCH_ALLOW to a comma separated list of hosts") + } + for _, h := range allow { + if strings.EqualFold(h, u.Hostname()) { + return u, nil + } + } + return nil, fmt.Errorf("host %q is not in FETCH_ALLOW", u.Hostname()) +} + +func allowlist() []string { + var out []string + for h := range strings.SplitSeq(os.Getenv("FETCH_ALLOW"), ",") { + if h = strings.TrimSpace(h); h != "" { + out = append(out, h) + } + } + return out +} + +// get does the GET and returns at most max bytes of the body; the rest is cut and truncated is set. +func get(ctx context.Context, client *http.Client, u string, max int64) (body string, truncated bool, err error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return "", false, err + } + resp, err := client.Do(req) + if err != nil { + return "", false, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode >= 400 { + return "", false, fmt.Errorf("server answered %s", resp.Status) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, max+1)) + if err != nil { + return "", false, err + } + if int64(len(data)) > max { + return string(data[:max]), true, nil + } + return string(data), false, nil +} + +type FetchIn struct { + URL string `json:"url" desc:"http or https URL on an allowed host" min:"1"` +} + +type Page struct { + Body string `json:"body"` + Truncated bool `json:"truncated"` +} + +// Example: failures are tool errors, so the model sees the reason and can react. +// +// @MCP.Tool("fetch_url", description="Fetches a URL with GET and returns the body as text (at most 256 KiB)") +// @MCP.Hint(readOnly, openWorld) +func FetchURL(ctx mcp.Context, in FetchIn) (Page, error) { + u, err := check(in.URL, allowlist()) + if err != nil { + return Page{}, mcp.ToolError(err.Error()) + } + // a redirect could leave the allowlist, so every hop is checked again + client := &http.Client{Timeout: timeout, CheckRedirect: func(r *http.Request, _ []*http.Request) error { + _, err := check(r.URL.String(), allowlist()) + return err + }} + body, truncated, err := get(ctx, client, u.String(), maxBody) + if err != nil { + return Page{}, mcp.ToolError("fetch failed: " + err.Error()) + } + return Page{Body: body, Truncated: truncated}, nil +} diff --git a/examples/fetch/fetch_test.go b/examples/fetch/fetch_test.go new file mode 100644 index 0000000..6e50a5b --- /dev/null +++ b/examples/fetch/fetch_test.go @@ -0,0 +1,54 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCheck(t *testing.T) { + cases := map[string]struct { + url string + allow []string + want string // part of the error, empty = allowed + }{ + "allowed": {"https://Example.com/x", []string{"example.com"}, ""}, + "empty denies": {"https://example.com", nil, "FETCH_ALLOW"}, + "other host": {"https://evil.test", []string{"example.com"}, "not in FETCH_ALLOW"}, + "subdomain": {"https://a.example.com", []string{"example.com"}, "not in FETCH_ALLOW"}, + "scheme": {"file:///etc/passwd", []string{"example.com"}, "http and https"}, + "relative": {"/etc/passwd", []string{"example.com"}, "http and https"}, + "port is fine": {"http://example.com:8080", []string{"example.com"}, ""}, + "userinfo trick": {"http://example.com@evil.test/", []string{"example.com"}, "not in FETCH_ALLOW"}, + } + for name, c := range cases { + _, err := check(c.url, c.allow) + if c.want == "" && err != nil || c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)) { + t.Errorf("%s: got %v, want %q", name, err, c.want) + } + } +} + +func TestGetLimitsBody(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/missing" { + http.NotFound(w, r) + return + } + _, _ = w.Write([]byte("0123456789")) + })) + defer srv.Close() + + body, cut, err := get(t.Context(), srv.Client(), srv.URL, 4) + if err != nil || body != "0123" || !cut { + t.Errorf("got %q, %v, %v", body, cut, err) + } + body, cut, err = get(t.Context(), srv.Client(), srv.URL, 10) + if err != nil || body != "0123456789" || cut { + t.Errorf("exact size must not be cut: got %q, %v, %v", body, cut, err) + } + if _, _, err = get(t.Context(), srv.Client(), srv.URL+"/missing", 10); err == nil { + t.Error("an error status must fail") + } +} diff --git a/examples/fetch/go.mod b/examples/fetch/go.mod new file mode 100644 index 0000000..a7c16fd --- /dev/null +++ b/examples/fetch/go.mod @@ -0,0 +1,7 @@ +module github.com/StevenCyb/example_fetch + +go 1.26.2 + +require github.com/StevenCyb/GoMCP v0.0.0 + +replace github.com/StevenCyb/GoMCP => ../.. diff --git a/examples/files/README.md b/examples/files/README.md new file mode 100644 index 0000000..47bc045 --- /dev/null +++ b/examples/files/README.md @@ -0,0 +1,28 @@ +# files + +A read-only browser for one directory, for a local client over stdio. + +- Resource template `file:///{path}`: reads a text file (up to 1 MiB). +- Tool `list_files`: the entries of a directory. +- Tool `search_files`: files whose name contains a text. + +The root is `FILES_ROOT` (default: the working directory). A path that leaves the root is refused +(`resolve` in `files.go`, tested in `files_test.go`). Symlinks inside the root are followed. + +```sh +FILES_ROOT=$HOME/notes gomcp stdio ./examples/files +``` + +Client config (build once, `gomcp stdio` compiles on every start): + +```sh +gomcp build ./examples/files ./bin/files +``` + +```json +{ + "mcpServers": { + "files": { "command": "/absolute/path/to/bin/files", "args": ["--stdio"], "env": { "FILES_ROOT": "/home/me/notes" } } + } +} +``` diff --git a/examples/files/files.go b/examples/files/files.go new file mode 100644 index 0000000..4e779fb --- /dev/null +++ b/examples/files/files.go @@ -0,0 +1,123 @@ +// Example: a read-only browser for a directory, meant to run over stdio as a local tool. +// The root comes from FILES_ROOT (default: the working directory). Every path a client +// sends goes through resolve, so nothing outside the root can be read. + +// @MCP.Server("files", version="1.0.0") +// @MCP.Instructions("Browse and read text files below one root directory. Paths are relative to it.") +package api + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/StevenCyb/GoMCP/pkg/mcp" +) + +const maxFileSize = 1 << 20 // larger files are refused + +var root string + +// @MCP.Setup +func Setup() error { + dir := os.Getenv("FILES_ROOT") + if dir == "" { + dir = "." + } + abs, err := filepath.Abs(dir) + root = abs + return err +} + +// resolve maps a client path to a path below root and fails when it would leave root. +// ponytail: symlinks inside root are followed; resolve them with EvalSymlinks if root holds untrusted links. +func resolve(root, rel string) (string, error) { + p := filepath.Join(root, filepath.FromSlash(rel)) // Join cleans the path, so ".." is already folded + back, err := filepath.Rel(root, p) + if err != nil || back == ".." || strings.HasPrefix(back, ".."+string(filepath.Separator)) { + return "", errors.New("path is outside the root") + } + return p, nil +} + +// search returns the slash separated paths of all files below root whose name contains substr. +func search(root, substr string) ([]string, error) { + out := []string{} + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.Contains(strings.ToLower(d.Name()), strings.ToLower(substr)) { + return err + } + rel, err := filepath.Rel(root, p) + out = append(out, filepath.ToSlash(rel)) + return err + }) + return out, err +} + +type FileURI struct { + Path string `uri:"path"` +} + +// Example: resource template for text files, e.g. file:///docs/readme.txt. +// +// @MCP.Resource("file:///{path}", title="File", mime="text/plain", description="Reads a text file below the root") +func Read(ctx mcp.Context, u FileURI) (mcp.Contents, error) { + p, err := resolve(root, u.Path) + if err != nil { + return nil, mcp.ErrNotFound + } + if info, err := os.Stat(p); err != nil || info.IsDir() || info.Size() > maxFileSize { + return nil, mcp.ErrNotFound + } + data, err := os.ReadFile(p) + if err != nil { + return nil, mcp.ErrNotFound + } + return mcp.Contents{mcp.TextContent(string(data))}, nil +} + +type ListIn struct { + Dir string `json:"dir,omitempty" desc:"Directory relative to the root, default: the root itself"` +} + +type Names struct { + Files []string `json:"files"` +} + +// @MCP.Tool("list_files", description="Lists the entries of a directory below the root; directories end with /") +// @MCP.Hint(readOnly, idempotent) +func ListFiles(ctx mcp.Context, in ListIn) (Names, error) { + p, err := resolve(root, in.Dir) + if err != nil { + return Names{}, mcp.ToolError(err.Error()) + } + entries, err := os.ReadDir(p) + if err != nil { + return Names{}, mcp.ToolError("cannot list " + in.Dir) + } + out := Names{Files: []string{}} + for _, e := range entries { + name := e.Name() + if e.IsDir() { + name += "/" + } + out.Files = append(out.Files, name) + } + return out, nil +} + +type SearchIn struct { + Query string `json:"query" desc:"Part of a file name, case-insensitive" min:"1"` +} + +// @MCP.Tool("search_files", description="Finds files below the root whose name contains the query") +// @MCP.Hint(readOnly, idempotent) +func SearchFiles(ctx mcp.Context, in SearchIn) (Names, error) { + found, err := search(root, in.Query) + if err != nil { + return Names{}, mcp.ToolError("search failed") + } + return Names{Files: found}, nil +} diff --git a/examples/files/files_test.go b/examples/files/files_test.go new file mode 100644 index 0000000..a406346 --- /dev/null +++ b/examples/files/files_test.go @@ -0,0 +1,49 @@ +package api + +import ( + "os" + "path/filepath" + "slices" + "testing" +) + +func TestResolveStaysInsideRoot(t *testing.T) { + root := t.TempDir() + for _, rel := range []string{"", "a.txt", "sub/a.txt", "sub/../a.txt", "/a.txt"} { + p, err := resolve(root, rel) + if err != nil { + t.Errorf("%q: %v", rel, err) + } else if r, err := filepath.Rel(root, p); err != nil || filepath.IsAbs(r) || r == ".." { + t.Errorf("%q -> %s is outside", rel, p) + } + } + bad := []string{"..", "../x", "sub/../../x", "a/../../../etc/passwd"} + if filepath.Separator == '\\' { + bad = append(bad, `..\x`) // a backslash is an ordinary character elsewhere + } + for _, rel := range bad { + if _, err := resolve(root, rel); err == nil { + t.Errorf("%q must be refused", rel) + } + } +} + +func TestSearch(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "sub"), 0o750); err != nil { + t.Fatal(err) + } + for _, f := range []string{"Notes.txt", "sub/more-notes.md", "other.go"} { + if err := os.WriteFile(filepath.Join(root, f), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + got, err := search(root, "NOTES") + if err != nil { + t.Fatal(err) + } + slices.Sort(got) + if !slices.Equal(got, []string{"Notes.txt", "sub/more-notes.md"}) { + t.Errorf("got %v", got) + } +} diff --git a/examples/files/go.mod b/examples/files/go.mod new file mode 100644 index 0000000..3d122a4 --- /dev/null +++ b/examples/files/go.mod @@ -0,0 +1,7 @@ +module github.com/StevenCyb/example_files + +go 1.26.2 + +require github.com/StevenCyb/GoMCP v0.0.0 + +replace github.com/StevenCyb/GoMCP => ../.. diff --git a/examples/hello/README.md b/examples/hello/README.md new file mode 100644 index 0000000..3c88198 --- /dev/null +++ b/examples/hello/README.md @@ -0,0 +1,18 @@ +# hello + +The smallest server: one tool, `hello`. Start here. + +```sh +gomcp serve ./examples/hello # http://127.0.0.1:8080/mcp +gomcp stdio ./examples/hello # stdin and stdout +``` + +Client config for stdio (build once, `gomcp stdio` compiles on every start): + +```sh +gomcp build ./examples/hello ./bin/hello +``` + +```json +{ "mcpServers": { "hello": { "command": "/absolute/path/to/bin/hello", "args": ["--stdio"] } } } +``` diff --git a/examples/hello/go.mod b/examples/hello/go.mod new file mode 100644 index 0000000..10597b5 --- /dev/null +++ b/examples/hello/go.mod @@ -0,0 +1,7 @@ +module github.com/StevenCyb/example_hello + +go 1.26.2 + +require github.com/StevenCyb/GoMCP v0.0.0 + +replace github.com/StevenCyb/GoMCP => ../.. diff --git a/examples/hello/hello.go b/examples/hello/hello.go new file mode 100644 index 0000000..4b8f315 --- /dev/null +++ b/examples/hello/hello.go @@ -0,0 +1,15 @@ +// Example: the smallest server, one tool. + +// @MCP.Server("hello", version="1.0.0") +package api + +import "github.com/StevenCyb/GoMCP/pkg/mcp" + +type HelloIn struct { + Name string `json:"name" desc:"Who to greet"` +} + +// @MCP.Tool("hello", description="Greets someone") +func Hello(ctx mcp.Context, in HelloIn) (string, error) { + return "Hello " + in.Name, nil +} diff --git a/examples/todo/README.md b/examples/todo/README.md new file mode 100644 index 0000000..a7521a6 --- /dev/null +++ b/examples/todo/README.md @@ -0,0 +1,29 @@ +# todo + +A todo list that survives restarts. + +- `Setup` loads the list from a JSON file, `Teardown` saves it when the server stops (end of input over stdio, Ctrl-C over HTTP). +- Tools `add_todo`, `list_todos`, `complete_todo`. +- Resource `todo:///open`: the open items. +- Prompt `plan_my_day`: asks the model to order the open items. + +The file is `TODO_FILE` (default `./todo.json`). A missing file is an empty list, a broken file stops the start. +The list is written only on a clean stop, so a killed server loses its changes. + +```sh +TODO_FILE=$HOME/todo.json gomcp serve ./examples/todo +``` + +Client config for stdio (build once, `gomcp stdio` compiles on every start): + +```sh +gomcp build ./examples/todo ./bin/todo +``` + +```json +{ + "mcpServers": { + "todo": { "command": "/absolute/path/to/bin/todo", "args": ["--stdio"], "env": { "TODO_FILE": "/home/me/todo.json" } } + } +} +``` diff --git a/examples/todo/go.mod b/examples/todo/go.mod new file mode 100644 index 0000000..ba99c61 --- /dev/null +++ b/examples/todo/go.mod @@ -0,0 +1,7 @@ +module github.com/StevenCyb/example_todo + +go 1.26.2 + +require github.com/StevenCyb/GoMCP v0.0.0 + +replace github.com/StevenCyb/GoMCP => ../.. diff --git a/examples/todo/todo.go b/examples/todo/todo.go new file mode 100644 index 0000000..014b7ef --- /dev/null +++ b/examples/todo/todo.go @@ -0,0 +1,147 @@ +// Example: a todo list that survives restarts. Setup loads it from a JSON file and +// Teardown saves it. The path comes from TODO_FILE (default: ./todo.json). + +// @MCP.Server("todo", version="1.0.0") +// @MCP.Instructions("Keep a todo list: add, list and complete items.") +package api + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "sync" + + "github.com/StevenCyb/GoMCP/pkg/mcp" +) + +type Item struct { + ID int `json:"id"` + Text string `json:"text"` + Done bool `json:"done"` +} + +var ( + mu sync.Mutex + items []Item + path string +) + +// load reads the list; a missing file is an empty list. +func load(path string) ([]Item, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []Item + return out, json.Unmarshal(data, &out) +} + +func save(path string, items []Item) error { + data, err := json.MarshalIndent(items, "", " ") + if err != nil { + return err + } + return os.WriteFile(path, data, 0o600) +} + +func open(items []Item) []Item { + out := []Item{} + for _, it := range items { + if !it.Done { + out = append(out, it) + } + } + return out +} + +// Example: load the file once on startup; an unreadable file stops the start. +// +// @MCP.Setup +func Setup() (err error) { + if path = os.Getenv("TODO_FILE"); path == "" { + path = "todo.json" + } + items, err = load(path) + return err +} + +// Example: write the list once on shutdown. Teardown cannot return an error, so it logs. +// +// @MCP.Teardown +func Teardown() { + mu.Lock() + defer mu.Unlock() + if err := save(path, items); err != nil { + fmt.Fprintln(os.Stderr, "todo: cannot save:", err) + } +} + +type AddIn struct { + Text string `json:"text" desc:"What to do" min:"1" max:"200"` +} + +type IDIn struct { + ID int `json:"id" desc:"Id of the item"` +} + +type List struct { + Items []Item `json:"items"` +} + +// @MCP.Tool("add_todo", description="Adds an item to the list") +func Add(ctx mcp.Context, in AddIn) (Item, error) { + mu.Lock() + defer mu.Unlock() + it := Item{ID: len(items) + 1, Text: in.Text} + items = append(items, it) + ctx.ResourcesChanged() + return it, nil +} + +// @MCP.Tool("list_todos", description="Lists all items, done and open") +// @MCP.Hint(readOnly) +func ListAll(ctx mcp.Context, _ struct{}) (List, error) { + mu.Lock() + defer mu.Unlock() + return List{Items: append([]Item{}, items...)}, nil +} + +// @MCP.Tool("complete_todo", description="Marks an item as done") +func Complete(ctx mcp.Context, in IDIn) (Item, error) { + mu.Lock() + defer mu.Unlock() + for i := range items { + if items[i].ID == in.ID { + items[i].Done = true + ctx.ResourcesChanged() + return items[i], nil + } + } + return Item{}, mcp.ToolError("no such item") +} + +// @MCP.Resource("todo:///open", mime="application/json", description="The open items") +func Open(ctx mcp.Context) (mcp.Contents, error) { + mu.Lock() + defer mu.Unlock() + return mcp.JSONContents(open(items)) +} + +// @MCP.Prompt("plan_my_day", description="Asks the LLM to plan the day around the open items") +func PlanMyDay(ctx mcp.Context, _ struct{}) (mcp.Messages, error) { + mu.Lock() + defer mu.Unlock() + var b strings.Builder + for _, it := range open(items) { + fmt.Fprintf(&b, "- %s\n", it.Text) + } + if b.Len() == 0 { + b.WriteString("(nothing open)\n") + } + return mcp.Messages{mcp.UserText("Plan my day. Order these open todos and suggest a time for each:\n" + b.String())}, nil +} diff --git a/examples/todo/todo_test.go b/examples/todo/todo_test.go new file mode 100644 index 0000000..8d4efbc --- /dev/null +++ b/examples/todo/todo_test.go @@ -0,0 +1,39 @@ +package api + +import ( + "os" + "path/filepath" + "slices" + "testing" +) + +func TestLoadSave(t *testing.T) { + file := filepath.Join(t.TempDir(), "todo.json") + + got, err := load(file) + if err != nil || len(got) != 0 { + t.Fatalf("a missing file is an empty list, got %v, %v", got, err) + } + + want := []Item{{ID: 1, Text: "a"}, {ID: 2, Text: "b", Done: true}} + if err := save(file, want); err != nil { + t.Fatal(err) + } + got, err = load(file) + if err != nil || !slices.Equal(got, want) { + t.Fatalf("round trip: got %v, %v", got, err) + } + if o := open(got); len(o) != 1 || o[0].ID != 1 { + t.Errorf("open: %v", o) + } +} + +func TestLoadRejectsBrokenFile(t *testing.T) { + file := filepath.Join(t.TempDir(), "todo.json") + if err := os.WriteFile(file, []byte("{broken"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := load(file); err == nil { + t.Error("a broken file must stop the start, not be overwritten") + } +} From dd8bded99dc45d644143962d1789d627fa2cbbae Mon Sep 17 00:00:00 2001 From: StevenCyb <41087154+StevenCyb@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:30:35 +0100 Subject: [PATCH 3/5] test: run the small examples through the stdio client Co-Authored-By: Claude Sonnet 5.5 --- e2e/examples_test.go | 75 ++++++++++++++++++++++++++++++++++++++++++++ e2e/stdio_test.go | 10 ++++-- 2 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 e2e/examples_test.go diff --git a/e2e/examples_test.go b/e2e/examples_test.go new file mode 100644 index 0000000..58d2c73 --- /dev/null +++ b/e2e/examples_test.go @@ -0,0 +1,75 @@ +// Examples test: build and run each small example over stdio and make one meaningful call. + +package e2e_test + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestExamples(t *testing.T) { + // the environment of the test process reaches the server, see runner.environment + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("file body"), 0o600)) + t.Setenv("FILES_ROOT", dir) + t.Setenv("TODO_FILE", filepath.Join(t.TempDir(), "todo.json")) + web := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("page body")) })) + t.Cleanup(web.Close) + t.Setenv("FETCH_ALLOW", "127.0.0.1") + + tests := map[string]func(t *testing.T, c *stdioClient){ + "hello": func(t *testing.T, c *stdioClient) { + t.Helper() + res := mustTool(t, c, "hello", obj{"name": "Ada"}) + assert.Equal(t, "Hello Ada", res["content"].([]any)[0].(obj)[keyText], "%v", res) + }, + "files": func(t *testing.T, c *stdioClient) { + t.Helper() + found := structured(t, mustTool(t, c, "search_files", obj{"query": "HELLO"})) + assert.Equal(t, []any{"hello.txt"}, found["files"]) + + read, rpcErr, _ := c.call("resources/read", obj{keyURI: "file:///hello.txt"}, nil) + require.Nil(t, rpcErr) + assert.Equal(t, "file body", read["contents"].([]any)[0].(obj)[keyText]) + + _, rpcErr, _ = c.call("resources/read", obj{keyURI: "file:///../secret.txt"}, nil) + assert.NotNil(t, rpcErr, "a path outside the root is not found") + res := mustTool(t, c, "list_files", obj{"dir": "../.."}) + assert.True(t, isError(res), "%v", res) + }, + "todo": func(t *testing.T, c *stdioClient) { + t.Helper() + mustTool(t, c, "add_todo", obj{keyText: "write tests"}) + mustTool(t, c, "add_todo", obj{keyText: "ship"}) + mustTool(t, c, "complete_todo", obj{"id": 1}) + + read, rpcErr, _ := c.call("resources/read", obj{keyURI: "todo:///open"}, nil) + require.Nil(t, rpcErr) + assert.Contains(t, read["contents"].([]any)[0].(obj)[keyText], "ship") + assert.NotContains(t, read["contents"].([]any)[0].(obj)[keyText], "write tests") + + prompt, rpcErr, _ := c.call("prompts/get", obj{keyName: "plan_my_day"}, nil) + require.Nil(t, rpcErr) + assert.Contains(t, prompt["messages"].([]any)[0].(obj)["content"].(obj)[keyText], "ship") + }, + "fetch": func(t *testing.T, c *stdioClient) { + t.Helper() + page := structured(t, mustTool(t, c, "fetch_url", obj{"url": web.URL})) + assert.Equal(t, "page body", page["body"]) + + res := mustTool(t, c, "fetch_url", obj{"url": "http://example.invalid/"}) + assert.True(t, isError(res), "a host outside FETCH_ALLOW is refused: %v", res) + }, + } + for name, run := range tests { + t.Run(name, func(t *testing.T) { + run(t, startStdio(t, "../examples/"+name)) + }) + } +} diff --git a/e2e/stdio_test.go b/e2e/stdio_test.go index 1fe3f45..74caa26 100644 --- a/e2e/stdio_test.go +++ b/e2e/stdio_test.go @@ -1,4 +1,4 @@ -// Stdio test: build and run example/ over stdin and stdout, like a client that starts the server itself. +// Stdio test: build and run examples/features/ over stdin and stdout, like a client that starts the server itself. package e2e_test import ( @@ -24,6 +24,12 @@ type stdioClient struct { } func startStdioExample(t *testing.T) *stdioClient { + t.Helper() + return startStdio(t, "../examples/features") +} + +// startStdio builds and runs the server in dir over pipes. +func startStdio(t *testing.T, dir string) *stdioClient { t.Helper() if testing.Short() { t.Skip("builds and runs the example") @@ -34,7 +40,7 @@ func startStdioExample(t *testing.T) *stdioClient { done := make(chan error, 1) go func() { - done <- runner.Serve(t.Context(), runner.Options{Dir: "../example", Stdio: true, Stdin: inR, Stdout: outW, Stderr: io.Discard}) + done <- runner.Serve(t.Context(), runner.Options{Dir: dir, Stdio: true, Stdin: inR, Stdout: outW, Stderr: io.Discard}) _ = outW.Close() }() go func() { From 51d99e8e0cd537306692c15b3b8fba9b15125987 Mon Sep 17 00:00:00 2001 From: StevenCyb <41087154+StevenCyb@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:30:35 +0100 Subject: [PATCH 4/5] doc: examples index, README and developer docs Co-Authored-By: Claude Sonnet 5.5 --- .github/pull_request_template.md | 2 +- README.md | 25 +++++++++++++++---------- README_DEV.md | 12 ++++++------ SECURITY.md | 2 +- examples/README.md | 17 +++++++++++++++++ 5 files changed, 40 insertions(+), 18 deletions(-) create mode 100644 examples/README.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 17956a2..c8a901b 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -6,5 +6,5 @@ - [ ] Tests added or updated (new behaviour starts with a failing test) - [ ] `golangci-lint run --path-mode=abs` and `go test -race ./...` pass -- [ ] New feature: `example/` shows it and `e2e/` tests it +- [ ] New feature: `examples/features/` shows it and `e2e/` tests it - [ ] README updated if the behaviour users see changed diff --git a/README.md b/README.md index fbaefb0..5cc19e1 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ revision (no sessions, no `initialize`, every request carries its protocol versi Older revisions are not supported. > **Status: v0.x.** The exported API of `pkg/mcp` may still change between minor versions. Requires Go 1.26.2 or newer. -> Code snippets in this document are abbreviated; runnable code is in [`example/`](example). +> Code snippets in this document are abbreviated; runnable code is in [`examples/`](examples). ## See It In 5 Seconds @@ -54,7 +54,12 @@ Get: - Input and output schemas derived from your Go types. - Auto-generated bootstrap (`main`, transport, auth, lifecycle wiring). -> A more advanced example for every feature is in the [example](example) directory. +> More runnable servers are in [`examples/`](examples) (index with how to run each): +> +> - [`files`](examples/files): read-only directory browser for a local client over stdio. +> - [`todo`](examples/todo): todo list kept in a JSON file, with Setup and Teardown. +> - [`fetch`](examples/fetch): URL fetcher with an allowlist, size limit and timeout. +> - [`features`](examples/features): every feature once. ## Why GoMCP @@ -64,7 +69,7 @@ You write the handler, GoMCP writes everything around it. - **Nothing lands in your module.** The generated code is built with Go's overlay mechanism: no generated files to commit or review, and no `go:generate` step. - **Remote or local from one codebase.** The same code runs as an HTTP server for many clients (`gomcp serve`) or as a local process that one client starts (`gomcp stdio`). - **The newest spec.** It implements MCP 2026-07-28 (stateless, `server/discover`, multi round-trip requests, tasks) from day one. -- **Tested end to end.** The example project runs through a test client over HTTP and stdio in CI on Linux and Windows, and a smoke test of every merged commit runs on Linux, Windows and macOS. +- **Tested end to end.** The `examples/features` project runs through a test client over HTTP and stdio in CI on Linux and Windows, and a smoke test of every merged commit runs on Linux, Windows and macOS. It has its own runtime (`pkg/mcp`), so you can also skip the annotations and register tools in code. If you prefer to write every registration yourself, or need a revision older than 2026-07-28, another MCP library for Go is the better fit. @@ -179,12 +184,12 @@ gomcp init ./hello --no-get # only write the files `build` compiles a single binary, `serve` builds and runs it as an HTTP server, `watch` rebuilds and restarts on every `.go` change and keeps the old server if a rebuild fails. `stdio` builds and runs it for a local client, see [Local or remote](#local-or-remote). ```sh -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 build ./examples/features ./bin/notes # one binary, contains both transports +gomcp serve ./examples/features # build + run over HTTP, Ctrl-C stops gracefully +gomcp watch ./examples/features # rebuild on change (HTTP only) +gomcp stdio ./examples/features # build + run over stdin and stdout +gomcp call ./examples/features # list the tools +gomcp call ./examples/features add_note '{"text":"hi"}' # call a tool, print the result gomcp version ``` @@ -202,7 +207,7 @@ flowchart LR `--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 +gomcp serve ./examples/features --addr 127.0.0.1:8765 --dotenv ./dev.env ``` ## Transports diff --git a/README_DEV.md b/README_DEV.md index ba4a268..f7943df 100644 --- a/README_DEV.md +++ b/README_DEV.md @@ -5,18 +5,18 @@ ```sh go vet ./... golangci-lint run --path-mode=abs # config: .golangci.yml, CI uses the latest release -go test -race ./... # includes e2e/, which builds and runs example/ (about a minute) -(cd example && go vet ./...) # example is its own module +go test -race ./... # includes e2e/, which builds and runs examples/ (about a minute) +for d in examples/*/; do (cd $d && go vet ./... && go test ./...); done # every example is its own module ``` -`e2e/` talks to `example/` like an MCP client and fails when a feature of the example has no test. A new feature needs +`e2e/` talks to `examples/features/` like an MCP client and fails when a feature of it has no test. A new feature needs an example and an e2e check. ## Test new feature -Write a MCP with a new feature (or modify example). Then run the service. +Write a MCP with a new feature (or modify examples/features). Then run the service. ```bash -go run ./cmd/gomcp serve ./example --addr 127.0.0.1:8765 +go run ./cmd/gomcp serve ./examples/features --addr 127.0.0.1:8765 ``` Create a `mcp.json` to configure the MCP connector if not present. The example's OAuth verifier is a stub that accepts @@ -52,7 +52,7 @@ go run ./cmd/gomcp call ./example add_note '{"text":"hi"}' Over stdio the client starts the server itself, so build once and point the client at the binary: ```sh -go run ./cmd/gomcp build ./example ./bin/notes +go run ./cmd/gomcp build ./examples/features ./bin/notes ``` ```json { diff --git a/SECURITY.md b/SECURITY.md index 00ce4a7..cc88340 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,6 +16,6 @@ Please do not open a public issue. Use GitHub's private vulnerability reporting per-user URIs and authorize them in the resource handler via `ctx.Principal()`. - Over stdio (`gomcp stdio`, `--stdio`, `GOMCP_TRANSPORT=stdio`) there is no authentication and scopes are not checked: the caller is the process that started the server. Only start it for clients you trust, and do not wire it to a network socket. -- `example/` uses a stub token verifier that accepts every non-empty token. Never copy it into production. +- `examples/features/` uses a stub token verifier that accepts every non-empty token. Never copy it into production. - Features of the example that check scopes (`@MCP.AuthScopes`) apply to tools, prompts, resources, completion and resource subscriptions. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..93a404e --- /dev/null +++ b/examples/README.md @@ -0,0 +1,17 @@ +# Examples + +Each directory is its own Go module with annotated Go files. Run one with `gomcp serve ./examples/` +(HTTP) or `gomcp stdio ./examples/` (stdin and stdout, for a client that starts it). + +| Example | Shows | Transport | +| --- | --- | --- | +| [`hello`](hello) | the smallest server: one tool | HTTP or stdio | +| [`files`](files) | read-only directory browser: resource template, two tools, path traversal protection | stdio | +| [`todo`](todo) | todo list in a JSON file: Setup and Teardown, tools, a prompt, a resource | HTTP or stdio | +| [`fetch`](fetch) | `fetch_url` with an allowlist, size limit and timeout, `ToolError` | HTTP or stdio | +| [`features`](features) | every feature once (auth, tasks, sampling, elicitation, ...), see its README | HTTP | + +The code is meant to be copied: copy a directory, change the module name and the `replace` line of its `go.mod` +(or drop it and `go get github.com/StevenCyb/GoMCP`). + +`go test ./...` inside an example runs its unit tests. `e2e/` builds and runs every example through a test client. From 7ae6a8311dbc034b9b292d022c07ace5b59ad348 Mon Sep 17 00:00:00 2001 From: StevenCyb <41087154+StevenCyb@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:02:20 +0100 Subject: [PATCH 5/5] doc: update example paths after rebase Co-Authored-By: Claude Sonnet 5.5 --- README_DEV.md | 8 ++++---- e2e/call_test.go | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README_DEV.md b/README_DEV.md index f7943df..fe7dedc 100644 --- a/README_DEV.md +++ b/README_DEV.md @@ -16,7 +16,7 @@ an example and an e2e check. Write a MCP with a new feature (or modify examples/features). Then run the service. ```bash -go run ./cmd/gomcp serve ./examples/features --addr 127.0.0.1:8765 +go run ./cmd/gomcp serve ./examples/featuress/features --addr 127.0.0.1:8765 ``` Create a `mcp.json` to configure the MCP connector if not present. The example's OAuth verifier is a stub that accepts @@ -44,15 +44,15 @@ Claude Code answers forms and URL pages itself in non-interactive runs, so use ` `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"}' +go run ./cmd/gomcp call ./examples/features +go run ./cmd/gomcp call ./examples/features add_note '{"text":"hi"}' ``` ## Test stdio Over stdio the client starts the server itself, so build once and point the client at the binary: ```sh -go run ./cmd/gomcp build ./examples/features ./bin/notes +go run ./cmd/gomcp build ./examples/featuress/features ./bin/notes ``` ```json { diff --git a/e2e/call_test.go b/e2e/call_test.go index f6ea3af..450e04e 100644 --- a/e2e/call_test.go +++ b/e2e/call_test.go @@ -1,6 +1,6 @@ package e2e_test -// TestCall runs gomcp call against example/: it builds it and talks over the stdio pipes like the command does. +// TestCall runs gomcp call against examples/features/: it builds it and talks over the stdio pipes like the command does. import ( "bytes" @@ -22,7 +22,7 @@ func TestCall(t *testing.T) { } 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) + err := caller.Run(t.Context(), runner.Options{Dir: "../examples/features", Stderr: io.Discard}, req, &out) return out.String(), err }