Commit graph go-sdk/examples/server
Author SHA1 Message Date
José M. Requena Plens
3f43bcf012
mcp: add HasParams so middleware can tell whether params are present (#1269)
This adds `mcp.HasParams(req Request) bool`, so a receiving middleware
can ask whether the message it was handed carried a `params` member.

The member is optional for several methods: `serverMethodInfos` sets
`missingParamsOK` for `server/discover`, `ping`, the four list methods
and the `cancelled`, `initialized` and `roots/list_changed`
notifications, so `{"jsonrpc":"2.0","id":1,"method":"tools/list"}` is a
complete request. For one of those, `unmarshalParams` returns a nil
`Params`, `newRequest` leaves `ServerRequest.Params` at the zero value
of `P`, and `GetParams` hands the middleware a non-nil interface holding
a typed nil pointer. Comparing that against nil says params are present,
and the first method called on it dereferences: `GetMeta` is promoted
from the embedded `Meta`. `Params` already declares `isNil` for
precisely this case, and it is unexported, so from outside the package
the accessor named after the question is the one thing that cannot be
reached.

`HasParams` is a function over `Request` rather than an exported method
on `Params` for two reasons. A middleware holds a `Request`, and this
way the caller never has to hold the value that panics. More
importantly, `isNil` cannot answer the question for every `Params`
value, so exporting it would ship a predicate that is itself unsafe: a
params type declared the documented way for a custom method, `struct{
mcp.ParamsBase }`, promotes `isNil` through a field selector, and that
dereferences the nil outer pointer before the method body runs. The
predicate therefore has to be computed from outside the value, and
`reflect.Value.IsNil` is what works for all of them.

Three judgement calls, stated so nobody has to find them.

First, `getRequestMeta` now goes through `HasParams`. That is a second
fix rather than a refactor: `AddReceivingCustomMethod` registers with
`missingParamsOK` too, so a client omitting `params` for a custom method
made `ServerRequest.ProtocolVersion`, `ClientInfo` and
`ClientCapabilities` panic in the promoted `isNil`. They now return
`""`, `nil` and `nil`. I could have left it out to keep the diff to one
function, but then the SDK would export a predicate that says to ask
before touching params while three of its own accessors still panicked
on the same value. If you would rather see it as a separate commit, say
so and I will split it.

Second, I did not add the predicate to the `Request` interface.
`Request` is sealed by `isRequest`, so a method would have been a
compatible change and would read slightly better at the call site, but a
free function leaves the interface alone and serves every `Request` just
as well.

Third, this reflects once per call of `getRequestMeta`. It is one
`reflect.ValueOf` on a value that is already an interface, on a path
where `newResult` already reflects per request.

Tests, both in `mcp/shared_test.go`.
`TestServerRequest_PerRequestAccessors_MissingParams` is the one that
fails before the change and passes after: on `main` it panics inside
`getRequestMeta` with `invalid memory address or nil pointer
dereference` from `(*customParams).isNil`, and here it asserts the three
accessors return zero values. `TestHasParams` covers the exported
behaviour: it builds exactly what `handleReceive` hands the middleware
chain for `tools/list`, `prompts/list`, `resources/list` and
`notifications/initialized` with no `params` member, asserts that
`GetParams` still returns a non-nil interface so the case under test is
still the typed-nil one, asserts `HasParams` reports false, and asserts
it reports true when params are present.

Behaviour an existing user would see change: only the three accessors
above, and only for a custom-method params type built on `ParamsBase`
whose `params` member was omitted, where a panic becomes a zero value.
Nothing about the wire format changes, no exported signature moves, and
no interface gains a method. A middleware that still writes
`req.GetParams() != nil` and then dereferences still panics; this gives
a caller the way to ask, it does not rescue a caller that does not.

Also here: one sentence on the doc comments of both
`AddReceivingMiddleware` methods saying a received message need not
carry params, since that is where a middleware author is reading, and
`examples/server/middleware/main.go` now logs `has_params` with
`mcp.HasParams` instead of the comparison that cannot work. The
example's printed output is unchanged, because the SDK client always
sends a `params` member for the methods it drives.

`go test ./...` and `gofmt -l .` are clean.

One thing to say plainly, since it is yours to decide and not mine: this
adds an exported symbol. `HasParams` is a new name in the public API of
`mcp`, and everything else here is doc comments, an example and the
three accessors. If you would rather not grow the surface for this, the
smaller answer is to keep the `getRequestMeta` fix and the doc-comment
sentence and drop the exported function, and a middleware author then
has the guarantee written down where they are reading even though they
still cannot ask the question in code. I prefer the function because the
guarantee alone leaves every middleware writing the same three lines of
`reflect`, and the one that does not write them panics on an ordinary
`tools/list`, but I will cut it to whichever shape you want.


Fixes #1261.

Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
2026-09-14 18:45:48 +02:00
Guglielmo Colombo
65ece59643
mcp: Allow registration of custom JSON-RPC methods (#956)
## Description

This PR introduces support for custom (non-standard) JSON-RPC methods in
the MCP Go SDK.
This feature enables servers to handle arbitrary JSON-RPC methods and
clients to invoke them, all while maintaining full type safety and
integrating seamlessly with the SDK's existing middleware and session
management.

- Server-Side Registration: Added AddReceivingCustomMethod to allow
servers to register handlers for custom methods. Incoming requests are
automatically unmarshaled into user-defined parameter structs.
- Client-Side Calling: Added AddSendingCustomMethod which returns a
strongly-typed caller function that clients can use to invoke custom
methods and receive strongly-typed results.
- Helper Structs: Provided ParamsBase and ResultBase for users to embed
in their custom structs. This allows them to easily satisfy the SDK's
internal Params and Result interfaces.

Fixes #954
2026-06-25 23:13:17 +02:00
Guglielmo Colombo
b6649db4f9
mcp: Deprecate roots, sampling and logging (SEP-2577) (#1017)
Fixes #1013
2026-06-23 11:11:08 +02:00
Max Gerber
2d47cc9664
auth: issuer mix-up mitigation (#859)
This PR functions as a Reference implementation of
[SEP-2468](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2468)
/ [RFC9207](https://datatracker.ietf.org/doc/rfc9207/).

This PR hardens the MCP OAuth Client functionality against Mix-Up
attacks:
>   Mix-up attacks aim to steal an authorization code or access token by
>   tricking the client into sending the authorization code or access
> token to the attacker instead of the honest authorization or resource
>   server

This PR hardens the client by adding support for a new `iss` parameter
in authorization responses:
- Authorization Servers broadcast support for the `iss` parameter via
the `authorization_response_iss_parameter_supported` metadata parameter
- If the parameter is supported, clients expect to receive the `iss`
parameter in the authorization response
- Clients compare the `iss` parameter in the authorization response to
the `Issuer` parameter in the authorization metadata. The two must match
exactly for the response to be processed.

Fixes #941
2026-05-27 11:39:08 +02:00
Oleksandr Redko
a1f808c86e
all: modernize code (#868)
Use `go fix ./...` to modernize the code.
2026-03-31 10:58:02 +02:00
Oleksandr Redko
b71a8391a6
all: fix typos (#869)
Grammar issues in docs, comments, and error messages.
2026-03-30 18:43:01 +02:00
Maciej Kisiel
4cdbaaf271
examples: add an example that display header forwarding. (#836)
Created to document the way it can be done discussed in #373.

Fixes #373
2026-03-10 10:57:55 +01:00
Theodor Nesfeldt Engøy
6a81e5da2a
examples: bind auth-middleware server to localhost by default (#784)
The auth-middleware example currently defaults to `-http :8080`, which
binds to all interfaces (LAN-exposed) by default.

This changes the default to `localhost:8080` and adds a short comment
noting `-http 0.0.0.0:8080` if you intentionally want to expose it.

Rationale: this example serves token-generation endpoints and
authenticated MCP routes; binding loopback by default avoids accidental
exposure while keeping the opt-in remote behavior.

---------

Co-authored-by: Theodor N. Engøy <theodornengoy@Mac.home>
Co-authored-by: Theodor N. Engøy <theodornengoy@eduroam-193-157-246-146.wlan.uio.no>
2026-02-11 10:02:17 +01:00
original-owl
86f8415122
mcp: use synctest for timing-dependent tests (#756)
Converted timing-based tests to use Go 1.25's synctest for instant,
deterministic execution with simulated time.

Moved converted tests to *_go125_test.go files. Tests using real I/O
(exec.Command, httptest) remain timing-based as they require actual
system operations.

Fixes #680

---------

Co-authored-by: i586147 <lakshana.goswami@sap.com>
2026-02-10 10:40:11 +01:00
Suraj Bobade
df4f0d56a4
mcp: use rand.Text and slog.DiscardHandler over internal implementation (#773)
Address TODOs in code requiring go 1.24 as minimum version

mcp/logging.go: use slog.DiscardHandler, over local implementation
mcp/util.go: use rand.Text, over local implementation

Fixes #772
2026-02-03 14:23:59 +01:00
Maciek Kisiel
367175d97b conformance: prepare the conformance test suite
- move the conformance related files to a dedicated directory
- simplify parts of the conformance script
- create a scaffolding for a new GitHub action to run conformance tests
- use the new --output-dir flag from the conformance suite for saving
  results on demand
2026-02-03 09:37:23 +01:00
Robert Findley
411d5a049a
mcp: switch icon theme to named string type (#733)
To be consistent with logging level, use a named string type for icon
themes. This improves readability / discoverability, and is more
consistent.

Updates #552
For #725
2025-12-19 16:44:10 -05:00
Robert Findley
b3399e6730
mcp: use args struct for CloseSSEStream (#718)
Change CloseSSEStream from func(time.Duration) to
func(CloseSSEStreamArgs) for forward compatibility, allowing new fields
to be added without breaking existing callers.
2025-12-11 15:13:38 -05:00
Eliya Sadan
d6d6edd6d4
auth: add OAuth 2.0 Protected Resource Metadata handler
This change adds support for RFC 9728 (OAuth 2.0 Protected Resource Metadata)
by introducing a `ProtectedResourceMetadataHandler`.

The handler includes built-in CORS support with `Access-Control-Allow-Origin: *`
by default, as OAuth metadata is public information meant for client discovery.

Documentation includes examples for using custom CORS policies with
popular middleware libraries (github.com/rs/cors and github.com/jub0bs/cors).

The implementation follows RFC 9728 §3.1 for OAuth 2.0 Authorization Server
Metadata discovery, enabling clients to discover protected resource capabilities
and authentication requirements.
2025-12-08 14:54:52 -05:00
Robert Findley
3b42db997c
examples: add a server for conformance testing (#681)
Add a server example for the new conformance test suite.

Passes all current conformance tests.

For #650
2025-12-08 10:32:21 -05:00
Robert Findley
21fb03dd1a
mcp: support url mode elicitation (#646)
Add initial support for URL mode elicitation, by introducing the new
types, as well as both server and client-side validation.

A follow-up CL will add support for ErrURLElicitationRequired.

For #623
2025-11-23 12:58:28 -05:00
Suraj Bobade
faddd764aa
Implement SEP-973 (#570)
mcp/protocol: Implement SEP-973

- Define Icon structure, which includes source, mimeType and sizes.
- sizes is any array of strings. refer
https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1531
- Support setting websiteUrl, icons for mcp.Implementation
- Support setting icons for mcp.Prompt
- Support setting icons for mcp.Tool
- Support setting icons for mcp.Resource

Fixes #552
2025-11-12 16:52:44 -05:00
Bo-Yi Wu
920e5a39ba
docs: improve documentation clarity and client integration steps (#567)
- Fix typo in "TroubleShooting" heading, changing it to
"Troubleshooting"
- Improve CLI usage instructions by formatting commands as code blocks
and marking them with "bash"
- Change "Start the Server" to a third-level heading for clarity
- Add additional code examples for real-world client testing and
interaction steps
- Clarify and condense instructions for adding the tool to a popular MCP
client

---------

Signed-off-by: appleboy <appleboy.tw@gmail.com>
Co-authored-by: Robert Findley <rfindley@google.com>
2025-10-13 11:47:58 -04:00
Robert Findley
964574b818
mcp: allow any value for schemas (#517)
As discussed at length in
https://github.com/modelcontextprotocol/go-sdk/issues/518, coupling our
schema fields to
jsonschema.Schema limits our user's ability to use a different schema
package, and makes it impossible for our client to talk to some
backends.

This CL relaxes the type of `*jsonschema.Schema` fields to be of type
`any`, which is a breaking change but is unlikely to affect most server
code. (It *is* a nontrivial change for clients).

Fixes https://github.com/modelcontextprotocol/go-sdk/issues/518
2025-09-26 11:55:54 -04:00
Jonathan Amsterdam
33ff851ef3
mcp: update to jsonschema that does not validate structs (#511)
Update to the latest jsonschema commit, which removes the ability to
validate structs and changes the type of ForOptions.TypeSchemas.
2025-09-22 15:28:04 -04:00
Suraj Bobade
8c42b69817
SSE: Add support for SSE handler options (#508)
mcp/sse: add support to provide for options for SSE transport

- Add SSEOptions struct to define SSE handler options.
- Update Signature of NewSSEHandler to accept SSEOptions [braking
change]
- Update unit test
- Update example test

Fixes https://github.com/modelcontextprotocol/go-sdk/issues/507,
https://github.com/modelcontextprotocol/go-sdk/issues/503
2025-09-19 13:01:57 -04:00
Robert Findley
28753c9f12
docs: document completion support (#495) 2025-09-18 14:27:35 -04:00
Jonathan Amsterdam
22f86c4dfd
internal/testing: add copyright header (#477) 2025-09-16 21:43:18 -04:00
Jonathan Amsterdam
a082e0764d
go.mod: update to jsonschema v0.2.1 2025-09-09 10:34:38 -04:00
Robert Findley
40b6bd30f1
all: add examples of customizing tool schemas, and clarify documentation (#421)
Add example/server/toolschemas, which demonstrates various ways to
customize tool schemas, and illustrates the differences between
ToolHandler and ToolHandlerFor.

Fixes #385
Fixes #386
For #368
2025-09-05 14:11:11 -04:00
Kason Braley
b774809086
examples: Update and fix outdated (#420)
Update examples/server/rate-limiting to use the same replace directive
strategy as the auth-middleware example, and fix the breakages.

Also remove the unneeded type parameters in examples/client/middleware.
2025-09-05 07:58:26 -04:00
ln-12
4257528dde
mcp: set default logging level to info (#411)
During initialization, the default logging level is set to info allowing
servers to emit logs immediately without waiting for a client to set a
log level.
The updated example shows how to send a notification in the context of
the request.

Fixes #387
2025-09-04 11:10:39 -04:00
Jonathan Amsterdam
92e19c1be8
examples/server/auth-middleware: remove custom middleware (#405)
The additional middleware added the TokenInfo the context.
RequireBearerToken already does that.
2025-09-03 17:27:38 -04:00
Jonathan Amsterdam
d0c5943f25
add HTTP Request to TokenVerifier (#404)
The request might be needed to verify the token.

Fixes #403.
2025-09-03 16:23:42 -04:00
Robert Findley
c76d991f05
examples/server/distributed: address comment in #380
I failed to push my branch before merging #380. Address one minor
comment from that PR.
2025-09-03 11:34:39 -04:00
Jonathan Amsterdam
0bb1a42b53
examples/server/middleware: log tool result (#400)
Log the result of a tool call in the middleware.

This example now fully demonstrates that receiving middleware can
effectively wrap a ToolHandler. That means that one reason for ToolFor
is moot: you don't need to get your hands on the returned ToolHandler in
order to wrap it.
2025-09-03 11:34:02 -04:00
Robert Findley
07b65d76a7
examples/server/distributed: a stateless distributed server
Add an example of a server that proxies HTTP requests to multiple
stateless streamable MCP backends.

For #148
2025-09-02 14:32:12 -04:00
Shusaku Yasoda
a3935c6be2
examples/server: add example MCP server with JWT and API key (#339)
This commit introduces a new example demonstrating the integration of
authentication middleware with an MCP server. The server supports both
JWT token and API key authentication, along with scope-based access
control for various MCP tools. Key features include token generation
endpoints, in-memory API key storage, and a health check endpoint.

New files added:
- `main.go`: Implements the MCP server and authentication logic.
- `go.mod` and `go.sum`: Manage dependencies for the project.
- `README.md`: Provides setup instructions, available endpoints, and
example usage.

This example serves as a reference for implementing secure access to MCP
tools.

Fixes #330
2025-09-02 11:49:46 -04:00
Sam Thanawalla
392f719bd1
mcp/examples: move server example into example folder (#357)
For better organization.
2025-08-26 09:13:30 -04:00
Jonathan Amsterdam
03c5113471
examples/server/memory: fix misleading code (#369)
Tools shouldn't both set StructuredContent and return a typed output.
Remove the assignment.
2025-08-25 16:48:10 -04:00
Rob Findley
9754a2aa86 examples: add an everything example, and simplify hello
Our 'hello' example should be as simple as possible. On the other hand,
we should have an 'everything' example that exercises (almost)
everything we offer.

Using the everything example, I did some final testing using the
inspector. This turned up a couple rough edges related to JSON null that
I addressed by preferring empty slices.

For #33
2025-08-22 14:00:37 -04:00
Sam Thanawalla
d16ce9c25f
mcp/examples: moves middleware examples into example folder (#356)
For better organization.
2025-08-22 11:18:05 -04:00
Sam Thanawalla
42f419fff4
mcp/examples: move elicitation example into example folder (#354)
Rename and move the example into the examples folder.
2025-08-22 11:01:48 -04:00
Jonathan Amsterdam
e3e8aaf024
mcp: align PromptHandler args with other handlers (#348)
The second arg is a GetPromptRequest.

Fixes #300.
2025-08-22 10:44:05 -04:00
Jonathan Amsterdam
6378df6f24
all: remove ServerRequest[T] for concrete T (#342)
Replace all occurrences of ServerRequest[*CallToolParams] and other
concrete instantiations with CallToolRequest and the like.

Make the XXXRequest types aliases, to preserve the convenience of
generics for the internal machinery (see shared.go, for example.)

I will expand the aliases in a followup PR.
2025-08-21 12:10:53 -04:00
Jonathan Amsterdam
5b1f328fd4
mcp: uncomment test, change struct{} to any (#341)
Address comments on #325.
2025-08-21 10:18:52 -04:00
Jonathan Amsterdam
32cf71de3a
mcp: change tool handler design (#325)
Change the design of tool handlers by removing genericity from the common path.
- `ToolHandler` gets the args as a `json.RawMessage`. Using Server.AddTool does no unmarshaling or schema validation.
- `ToolHandlerFor`, installed with `AddTool`, are the only generic pieces.

TODO:
uncomment and fix some tests
2025-08-20 19:36:34 -04:00
Jonathan Amsterdam
6e03217c83
mcp: introduce Requests (#267)
Handlers and client/server methods take a single request argument
combining the session and params. This slightly simplifies the signature
for handlers, since there is no longer an often-ignored session
argument.

But more importantly, it opens the door to adding more information in
requests, such as auth info and HTTP request headers.

For #243.
2025-08-12 17:49:50 -04:00
Robert Findley
e097918484
mcp: make transports open structs
As described in #272, there is really no reason for transports to be
closed structs with constructors, since their state must be established
by a call to Connect. Making them open structs simplifies their APIs,
and means that all transports can be extended in the future: we don't
have to create empty Options structs just for the purpose of future
compatibility.

For now, the related constructors and options structs are simply
deprecated (with go:fix directives where possible). A future CL will
remove them prior to the v1.0.0 release.

For #272
2025-08-12 15:14:21 -04:00
Rob Findley
e00c485969 examples: add a 'listeverything' client example, and reorganize
Add a client example that lists all features on a stdio server. Since
this is our first client example, organize examples by client / server
-- otherwise it is too difficult to find client examples.

For #33
2025-08-06 11:46:59 -04:00