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
2 changes: 1 addition & 1 deletion .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
5 changes: 2 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 15 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -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
```

Expand All @@ -202,7 +207,7 @@ flowchart LR
`--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
gomcp serve ./examples/features --addr 127.0.0.1:8765 --dotenv ./dev.env
```

## Transports
Expand Down
16 changes: 8 additions & 8 deletions README_DEV.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/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
Expand Down Expand Up @@ -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 ./example ./bin/notes
go run ./cmd/gomcp build ./examples/featuress/features ./bin/notes
```
```json
{
Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
26 changes: 13 additions & 13 deletions cmd/gomcp/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,49 +82,49 @@ 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)
}

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)
}
}

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)
}

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")
}

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 {
Expand Down Expand Up @@ -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)
}
Expand All @@ -210,15 +210,15 @@ 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)
assert.Equal(t, "local.env", f.opts.DotEnv)
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)
Expand All @@ -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)
Expand All @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions e2e/call_test.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
}

Expand Down
75 changes: 75 additions & 0 deletions e2e/examples_test.go
Original file line number Diff line number Diff line change
@@ -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))
})
}
}
4 changes: 2 additions & 2 deletions e2e/features_test.go
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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()
Expand Down
10 changes: 8 additions & 2 deletions e2e/stdio_test.go
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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")
Expand All @@ -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() {
Expand Down
17 changes: 17 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Examples

Each directory is its own Go module with annotated Go files. Run one with `gomcp serve ./examples/<name>`
(HTTP) or `gomcp stdio ./examples/<name>` (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.
Loading
Loading