Commit graph go-sdk/mcp
Author SHA1 Message Date
Robert Findley
b615fa49b1
mcp: add a streamable serving benchmark
Add a benchmark using the streamable HTTP handler, and a more realistic input/output signature. Also expose this handler as an example (both a go example and a server in the examples/ directory).
2025-09-17 17:49:31 -04:00
Rob Findley
a3e753b8d8 mcp: correct the JSON used for unstructured content
Recently, I refactored to fix validation and default application for
structured output. However, I used the wrong byte slice for the
unstructured output. Fix it to use the same bytes as structured output,
with a test.

Fixes #475
2025-09-17 17:42:43 -04:00
Rob Findley
bd6ffe3b4c mcp: add an example customizing a nested type schema
Add an example that demonstrates how to customize a nested type schema,
which is a recurring problem for our users (see #467).

Fixes #467
Updates #368
2025-09-16 21:34:27 -04:00
Rob Findley
845c29f6b7 mcp: add a benchmark for the MemoryEventStore; remove validation
Add a new benchmark measuring the append and purge performance of the
MemoryEventStore. This benchmark revealed that the store is orders of
magnitude slower than it should be due to conservative validation
(hugely so: 300KB/s vs 568MB/s). Turn off this validation by default.

For #190
2025-09-16 15:50:31 -04:00
Robert Findley
ac2f175214
docs: add feature and troubleshooting documentation (#463)
Add a framework for feature documentation, and start populating it with
our SDK documentation.

This framework is as follows:
- internal/docs/**.src.md is the markdown source for the docs/
  directory.
- The x/example/internal/cmd/weave tool is used to compile these docs to
  the top-level docs, supporting both linked code samples and generated
  tables of contents.
- The readme-check workflow is updated to check these docs as well.
- The structure of these docs follows the MCP spec.
- Wherever possible, example code is linked from actual Go documentation
  examples, so that it is testable.

Some minor modifications to the weave tool were made to support this
framework.

Additionally, partially fill out this documentation with content on
base protocol and client features, as well as troubleshooting help.

Along the way, a bug was encountered that our LoggingTransport was not
concurrency safe. This is fixed with a mutex.

Fixes https://github.com/modelcontextprotocol/go-sdk/issues/466
Fixes https://github.com/modelcontextprotocol/go-sdk/issues/409
Updates https://github.com/modelcontextprotocol/go-sdk/issues/442
2025-09-16 11:13:40 -04:00
Jonathan Amsterdam
ab4d6218c6 mcp: tweak ProgressNotificationParams 2025-09-16 10:37:47 -04:00
Rob Findley
159933cfa3 mcp: speed up TestCommandTransportDuration
At 7s, this test was 70% of our test execution time on my computer.
Speed it up by mutating the defaultTerminateDuration for the purposes of
the test.

Also update our test workflow to use go1.25, now that it's out.
2025-09-12 12:00:29 -04:00
Rob Findley
9f1b8646bd mcp: propertly validate against JSON, independent of Go values
Our validation logic was avoiding double-unmarshalling as much as
possible, by parsing before validation and validating the Go type.

This only works if the Go type has the same structure as its JSON
representation, which may not be the case in the presence of types with
custom MarshalJSON or UnmarshalJSON methods (such as time.Time).

But even if the Go type doesn't use any custom marshalling, validation
is broken, because we can't differentiate zero values from missing
values.

Bite the bullet and use double-unmarshalling for both input and output
schemas. Coincidentally, this fixes three bugs:
- We were accepting case-insensitive JSON keys, since we parsed first,
  even though they should have been rejected. A number of tests were
  wrong.
- Defaults were overriding present-yet-zero values, as noted in an
  incorrect test case.
- When "arguments" was missing, validation wasn't performed, no defaults
  were applied, and unmarshalling failed even if all properties were
  optional.

First unmarshalling to map[string]any allows us to fix all these bugs.
Unfortunately, it means a 3x increase in the number of reflection
operations (we need to unmarshal, apply defaults and validate,
re-marshal with the defaults, and then unmarshal into the Go type).
However, this is not likely to be a significant overhead, and we can
always optimize in the future.

Update github.com/google/jsonschema-go to pick up necessary improvements
supporting this change.

Additionally, fix the error codes for invalid tool parameters, to be
consistent with other SDKs (Invalid Params: -32602).

Fixes #447
Fixes #449
Updates #450
2025-09-12 10:50:19 -04:00
Sam Thanawalla
b66679350e
transport.go: disable stdio batching for newer protocols (#453)
This PR disables batching support for stdio by storing the negotiated
protocol version and comparing it to protocolVersion20250618.

Fixes: #21
2025-09-11 13:33:46 -04:00
ankitm123
bf3ff50a16 mcp: remove json-rpc batching for more recent protocol versions
JSON-RPC batching support is removed for protocol versions greater than or
equal to protocolVersion20250618

Fixes #21
2025-09-11 10:50:56 -04:00
Rob Findley
872b437b2a internal/readme: use go:generate rather than Make
Simplify the readme generation to just use go:generate, no longer
depending on Make or bash.

Subsequent CLs will generate more documentation in a similar manner.

For #442
2025-09-11 10:38:07 -04:00
Sam Thanawalla
3a66cf3997
go.mod: update jsonschema to v0.2.2 (#446)
This version of jsonschema fixes embedded structs.

Fixes: #437
2025-09-11 10:21:02 -04:00
Rob Findley
728e0e3ac9 mcp: improve error messages from Wait for streamable clients
Previously, the error message received from ClientSession.Wait would
only report the closeErr, which would often be nil even if the client
transport was broken. Wait should return the reason the session
terminated, if abnormal.

I'm not sure of the exact semantics of this, but surely returning nil is
less useful than returning a meaningful non-nil error. We can refine our
handling of errors once we have more feedback.

Also add a test for client termination on HTTP server shutdown,
described in #265. This should work as long as (1) the session is
stateful (with a hanging GET), or (2) the session is stateless but the
client has a keepalive ping.

Also: don't send DELETE if the session was terminated with 404; +test.

Fixes #265
2025-09-10 11:24:26 -04:00
Rob Findley
b1c75f04d8 mcp: remove deprecated transport constructors
In #272, we made transports open structs and deprecated their
constructors. However, we left the constructors in place to allow go:fix
directives to facilitate migration.

Now let's remove the constructors before cutting the release.

Fixes #305
2025-09-10 11:21:46 -04:00
Rob Findley
5bbca40032 mcp: fix typo in protocolVersion20241105
This version was so last year.

Fixes #432
2025-09-09 11:21:18 -04:00
Clément RUFFINONI
bae3558d49
mcp: allow configurable terminate duration for CommandTransport (#363)
Make the process termination timeout configurable instead of using a
hardcoded 5-second delay. This allows applications to customize the
termination behavior based on their specific needs.

Fixes #322.
2025-09-08 13:28:32 -04:00
Rob Findley
4656930de8 mcp: avoid "null" when tools fail to return content
For some reason, this was a regression from v0.3.1, for some of our
examples. Fix it and address the existing TODO.
2025-09-05 16:57:02 -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
Rob Findley
5ccd97fafc mcp: allow requests before notifications/initialized
Upon a closer reading of the spec, it is OK for the server to response
to client requests before it has received notifications/initialized (as
long as it has received initialize). This effectively rolls back the fix
from #225.

Some hooks are left for enforcing strictness around server->client
requests prior to initialized. These will be revisited in subsequent
CLs.

For #395
2025-09-05 12:04:58 -04:00
Rob Findley
9d34aff732 mcp: avoid "null" in structuredContent
Avoid a typed nil in structuredContent (yet another typed nil), leading
to "null" on the wire.

Fixes #417
2025-09-04 19:48:51 -04:00
Rob Findley
ee5141621c mcp: be strict about returning the Mcp-Session-Id header
Rather than returning the Mcp-Session-Id header for all responses, only
return it from initialize, per the spec.

Fixes #412
2025-09-04 15:34:05 -04:00
Rob Findley
2c40bdc4d7 mcp: systematically improve streamable client errors
The streamable client connection can break for a variety of reasons,
asynchronously to the client's request. Decorate these failures with
additional context to clarify why they occurred.

Add a test for the failure message of #393.

Fixes #393
2025-09-04 14:09:37 -04:00
Rob Findley
a4313f92bf mcp: refactor the streamable client test to be more flexible
Use a fake streamable server to facilitate testing client behavior.
For this commit, just update the existing test (moved to a new file for
isolation). Subsequent CLs will add more tests.

Improve one client error message that occurred while debuging tests.

For #393
2025-09-04 14:09:37 -04:00
Jonathan Amsterdam
30261728f7
mcp: validate user-provided output schemas (#408)
toolForErr was ignoring the output schema if the output type was any.
That neglected the case where the user provided their own output schema.

Fixes #371.
2025-09-04 14:04:27 -04:00
Rob Findley
07b9cee8cc mcp: flush headers immediately for the hanging GET
Flush headers immediately for the persistent hanging GET of the
streamable transport; otherwise, clients may time out.

Fixes #410
2025-09-04 12:40:07 -04:00
Jonathan Amsterdam
203792dfdc
mcp: improve docs around tool handlers (#414) 2025-09-04 11:13:17 -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
Rob Findley
a1eb4849b7 mcp: correctly disallow GET requests on stateless servers
The condition sessionID == "" was not quite right for disallowing GET
requests. Since we decided to differentiate "stateless" vs "sessionless"
servers, we need to disallow GET requests for both.

For #393
2025-09-03 19:25:25 -04:00
Jonathan Amsterdam
8314ec099b
mcp: validate tool output (#352)
Validate the handler's returned output against the output schema of a tool.

Fixes #301.
2025-09-03 16:25:48 -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
ccpro
1c20560beb
mcp: export jsonResponse field
Exporting StreamableHTTPOptions.JSONResponse is helpful for some users behind proxies that don't work well with text/event-stream.

For #211

Co-authored-by: ccpro10 <co1797249167@gmail.com>
2025-09-03 11:35:19 -04:00
Jonathan Amsterdam
063fb12149
mcp: unexport ToolFor (#402)
The rationale is provided on the issue.

Also, document the low-level nature of Server.AddTool. (drive-by change)

Fixes #401.
2025-09-03 11:33:40 -04:00
Jonathan Amsterdam
7769b2a959
mcp: set content to marshaled output (#398)
The ToolHandler constructed by ToolFor sets the result's Content to the
marshaled output, following the spec's suggestion.

See
https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content.

Also, set StructuredContent to the marshaled RawMessage to avoid a
double marshal.

Fixes #391.
2025-09-03 10:37:27 -04:00
Jonathan Amsterdam
7bfde44981
mcp: statically type the server-side tool params (#378)
Introduce CallToolParamsRaw on the server side, so that tool handlers
see in the type system that a tool's arguments are a json.RawMessage.

Fixes #377.
2025-08-30 08:16:06 -04:00
Sam Thanawalla
ddaf35ed77
mcp/streamable: use event store to fix unbounded memory issues (#335)
This CL utilizes the event store to write outgoing messages and removes
the unbounded outgoing data structure.

It also adds a new interface [EventStore.Open]

For #190
2025-08-29 12:54:51 -04:00
Huabing (Robin) Zhao
f6118aaace
mcp: fix the type of the Complete handler
The Complete handler was returning an abstract Result type, rather than concrete CompleteResult type.

Fixes #375
2025-08-29 10:06:23 -04:00
Takeshi Yoneda
a76bae3a11 address review comments
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2025-08-27 16:03:32 -04:00
Takeshi Yoneda
c24d9856c4 mcp/streamable: fixes broken DELETE request on connection close
Signed-off-by: Takeshi Yoneda <t.y.mathetake@gmail.com>
2025-08-27 16:03:32 -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
Jim Clark
c1c22925da
relax requirements on resource URIs (#365)
remove checks for URI scheme; nothing in the spec requires one

# Background

When adding resource templates, we are currently doing checks for
schemes on absolute uris. It is still common for MCP servers to use
custom uris that would not pass these checks. For example, if the
official GitHub MCP server were to use this sdk, it would show failures
like:

```
"repo://{owner}/{repo}/contents{/path*}": parse "repo://{owner}/{repo}/contents{/path*}": invalid character "{" in host name
"repo://{owner}/{repo}/refs/heads/{branch}/contents{/path*}": parse "repo://{owner}/{repo}/refs/heads/{branch}/contents{/path*}": invalid character "{" in host name
"repo://{owner}/{repo}/sha/{sha}/contents{/path*}": parse "repo://{owner}/{repo}/sha/{sha}/contents{/path*}": invalid character "{" in host name
invalid resource template uri "repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}": parse "repo://{owner}/{repo}/refs/pull/{prNumber}/head/contents{/path*}": invalid character "{" in host name
"repo://{owner}/{repo}/refs/tags/{tag}/contents{/path*}": parse "repo://{owner}/{repo}/refs/tags/{tag}/contents{/path*}": invalid character "{" in host name
```

The wikipedia MCP would also show problems with missing schemes.

```
"/search/{query}": <nil>
"/article/{title}": <nil>
"/summary/{title}": <nil>
"/summary/{title}/query/{query}/length/{max_length}": <nil>
"/summary/{title}/section/{section_title}/length/{max_length}": <nil>
"/sections/{title}": <nil>
"/links/{title}": <nil>
"/facts/{title}/topic/{topic_within_article}/count/{count}": <nil>
"/coordinates/{title}": <nil>
```
2025-08-25 15:00:36 -04:00
Rob Findley
f37e549e25 mcp: polish package doc for v0.3.0
Do a pass through the package doc for v0.3.0.
2025-08-22 16:03:15 -04:00
Hongxiang Jiang
fb69971650
mcp: cleanup transport after keepalive ping fails
An onClose function is passed to the ServerSession and ClientSession to
help cleanup resources from the caller.

The onClose function will be executed as part of the ServerSession and
ClientSession closure.

Fixes #258
2025-08-22 15:26:52 -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
Jonathan Amsterdam
c631641296
mcp: check output schema type (#358)
Server.AddTool now checks that an output schema, if any, has type
"object".

Also add doc and a test.
2025-08-22 11:35:50 -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
Jonathan Amsterdam
b891d95361
mcp: example middleware wrapping ToolHandler (#351)
Add to the middleware example to show how to wrap a ToolHandler.

This middleware is very close to, but not the same as, wrapping a
ToolHandler directly. The only difference is that the middleware wraps
Server.callTool, which looks up the tool by name in the server's list
and then calls the handler. That lookup (plus other intervening
middleware, of course) is all that distinguishes this way of wrapping
from a more direct wrapping.
2025-08-22 11:05:03 -04:00
Jonathan Amsterdam
18c96d6912
mcp: enforce input schema type "object" (#349)
The spec makes it clear that input schemas must have type "object".
Enforce that.
Allow "any" as an input argument type by special-casing it.

Fixes #283.
2025-08-22 11:04:44 -04:00
Jonathan Amsterdam
4587941994
mcp: add Request.GetExtra (#350) 2025-08-22 11:04:01 -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