Repository navigation
Let operators set the instructions MCP endpoints return - #7280
Conversation
MCP clients add a server's instructions to the model's context while the server is connected. Operators need to add policy or usage guidance there without rebuilding the server, and ToolHive had no way to do it. Add an optional instructions field (mode, value) to MCPServer, MCPRemoteProxy and VirtualMCPServer, backed by a type in pkg/mcp/instructions that the CRDs, the RunConfig and the vMCP config share. A new middleware sets the instructions of successful initialize and server/discover results: replace returns the value, and append and prepend join it to the server's text with a blank line. It reads JSON and event-stream bodies, including the legacy SSE GET stream, and passes every other response through unread. The operator maps the field into the RunConfig, vMCP applies the same middleware to its endpoint, and thv run gains --instructions-file and --instructions-mode. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #7280 +/- ##
==========================================
+ Coverage 82.46% 82.52% +0.06%
==========================================
Files 937 939 +2
Lines 95869 96395 +526
==========================================
+ Hits 79060 79552 +492
- Misses 16804 16838 +34
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The SDK publishes the new InstructionsConfig schema, so the deliberate schema count in the generated-invoker contract test moves to 211. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Nice feature, and the test coverage across transports is thorough. Most of my comments are inline. The main ones are making this fail closed like the tool filter, and scoping the GET handling to legacy SSE.
A few things that aren't in the diff:
pkg/api/v1/workload_service.go: when a workload is edited through the API,BuildFullRunConfigrebuilds the RunConfig from the request, and instructions set withthv run --instructions-fileget dropped. Change an env var in Studio and after the restart clients no longer see the policy text, with nothing to tell anyone. Couldpersisted.Instructionsbe carried over viaWithInstructions(beforeWithMiddlewareFromFlags), the same way the upgrade applier keeps it? I don't think the API needs to be able to set it in this PR; a "not supported via API yet" note like the one for token exchange is enough.pkg/export/k8s.godoesn't copyInstructionsinto the exportedMCPServer, sothv exportdrops it.docs/arch/02-core-concepts.mdhas a list of middleware types that's missinginstructions.- Some untested paths in the middleware: 1xx before the final status,
WriteHeadercalled twice,Unwrap/http.ResponseController, an event stream withContent-Encoding, an empty 2xx body (the "no result" warning infinish), and warn-once.
Resolve the vMCP chain conflicts with the call-binding middleware: instructions sits between call binding and classification, in the code, the chain comment and the pipeline table. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
A value is now used without leading and trailing white space, so a file that ends in a newline or a YAML block adds no blank line. A value that is only white space, or longer than 65536 characters, is rejected by Validate and by the CRD schema. The RunConfig ConfigMap holds the value twice, and the bound keeps both copies well under the 1 MiB limit. A VirtualMCPServer may set spec.instructions or spec.config.instructions but no longer both, and vmcp validate checks instructions the way serve does at startup. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Editing a workload through the API rebuilt its RunConfig from the request and dropped instructions set with thv run, so clients stopped seeing them after the restart. The API cannot set instructions yet, so an edit now carries the persisted ones over, as the upgrade applier does. thv export copies them into the exported MCPServer. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
The middleware treated every GET as a possible legacy SSE stream. On Streamable HTTP a GET stream never carries an initialize or server/discover result, so it decoded every notification for the life of the connection. The transport is now fixed when the middleware is configured: on legacy SSE it reads GET streams and leaves POST responses alone, and otherwise it reads POST responses only. vMCP serves Streamable HTTP, so it never reads a GET stream. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
A server could keep the configured text from clients by sending a response the middleware forwarded unread: duplicate or case-variant members, a content coding, a body over the bound, or bare-CR line endings, which also left a legacy SSE stream held until it closed. The middleware now withholds such a response, as the tool filter does, and answers with a JSON-RPC internal error: under HTTP 500 for a JSON body, as an error event on the stream that answers a POST, and on the legacy SSE stream as an error event when the event names an id. A 2xx answer to a POST that never carries the result is withheld too. The bound on what it holds drops to 1 MiB and is checked before a write is taken in, a failed write reaches the handler, the instructions member must be unique and canonical, and legacy SSE failures are logged. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Word the RunConfig field comment, which becomes the public API and SDK description, for users. List instructions with the other middleware types and RunConfig fields, say that the middleware_configs entry is what takes effect in an exported RunConfig, and fix an ordering note that named the wrong middleware. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged origin/main in dc3f780. The only conflicts were in the vMCP chain next to the new call-binding middleware, and the regenerated files are clean. From the review body:
|
A result in an event of another type set the search done, so a decoy under event: foo let the real result that followed through unread. The middleware still reads and rewrites every event, whatever its type, since the go-sdk legacy SSE client dispatches every type as a message. Only an event without a type or of type message, which every client dispatches, now ends the search, on the legacy SSE stream and on the stream that answers a POST alike. An event of another type that has to be withheld is dropped rather than replaced by an error event, which clients that skip that type would read as their answer. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
ChrisJBurns
left a comment
There was a problem hiding this comment.
See the inline comments.
A stream a GET opened answers no single request, yet the middleware stopped at the first InitializeResult-shaped result, so a decoy with another id let the real one through unread. It now reads such a stream for as long as it lasts and rewrites every result that names protocolVersion, serverInfo or supportedVersions under any spelling a decoder binds. An event whose bytes name none of them passes without being decoded, so the cost is a byte check per event. An event over 16 MiB is withheld alone and the stream goes on, and a line clients split differently makes the stream pass as it arrives, ending it if it then names one of those members. On Streamable HTTP, a GET with Last-Event-ID resumes a stream that may replay the initialize or server/discover result, so it is read the same way. A withheld stream used to stay open while delivering nothing, and a GET answered with the error never finished. The error now carries its own Content-Length and is flushed, and once a stream or a GET is withheld the handler's next write returns an error, so it stops and the client sees the response end. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
ChrisJBurns
left a comment
There was a problem hiding this comment.
See the inline comments.
On a stream a GET opened, any event over 16 MiB was withheld unread. On legacy SSE that stream carries every response, so a large tool or resource result became an internal error once instructions were set, for clients that set no size limit of their own. An oversized event whose bytes name no result member is now forwarded as it arrives while its bytes are still checked, and only one that may name a result member is withheld. When the name shows after part of the event has been forwarded, the stream ends. A byte order mark at the start of an event stream made the first event's type unreadable here while clients strip it, so an event typed foo could end the search on the stream that answers a POST. The marks are now dropped before lines are read, as the tool filter does. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Thanks for working through all of that. I've checked every thread against a0fc8944e, and all the fixes are in and tested. Two things before this can go in: it conflicts with main now (mcpserver_types.go and crd-api.md), and there's one new issue with the raw mode on GET streams, inline below. The E2E failure is an etcd timeout in kind, so a rerun should clear it.
Tiny nit: in workload_service_test.go, TestBuildFullRunConfig_KeepsPersistedInstructions landed between the docstring of TestBuildFullRunConfig_NoOtelConfigLeavesTelemetryNil and its function.
Resolve the MCPServerSpec conflict by keeping instructions next to the reworded externalAuthConfigRef comment, renumber the vMCP pipeline table around the instructions row, and regenerate the CRD API docs. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
One line separator put a GET stream into a raw mode for good, after which any later mention of serverInfo or protocolVersion ended the stream. U+2028 and NEL appear unescaped in ordinary JSON.stringify and pydantic output, so a tool result with a pasted paragraph could cost a legacy SSE client its session. Every client agrees where an event ends, so such an event is now decided alone: a split inside a data value does no harm and the event is read as usual, and one elsewhere withholds the event only if it may name a result member. Raw mode is gone, leaving the GET path with events, skipping and forwarding. An oversized event forwarded in pieces that names a result member only later is now cut short with a blank line and withheld alone, as one that arrives in one write is, instead of ending the stream. Only a server that ends lines with a bare CR, which leaves no event end every client agrees on, still has its stream ended. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
The CRD's \S pattern is checked with RE2, where \s is ASCII only, while Validate and Apply trimmed all Unicode white space. A value of only no-break spaces passed admission and then failed in the controller. Validate and Apply now trim tab, LF, FF, CR and space, which is what the pattern recognises, so both agree, and other white space is kept as text. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
The vMCP comment said the middleware leaves GET streams alone, but it reads a GET with Last-Event-ID. The workload service test sat between another test's doc comment and its function. Signed-off-by: Aron Gates <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged origin/main in cdcab4f. The conflicts were the MCPServerSpec comment next to |
jhrozek
left a comment
There was a problem hiding this comment.
Thanks for addressing the review feedback. The follow-up commits and tests cover the issues raised in the review threads.
Two items from the earlier local review remain as follow-ups: flushed comment-only SSE keepalives can still be buffered until an event boundary, and the published Swagger schema does not encode the instructions validation constraints. Approving with those limitations noted.
Summary
MCP clients add a server's
instructionsto the model's context while the server is connected. Operators need to put policy or usage guidance there without rebuilding the server, and ToolHive had no way to do it.instructionsfield (mode,value) to MCPServer, MCPRemoteProxy and VirtualMCPServer, in both served API versions. The type lives inpkg/mcp/instructionsand is shared by the CRDs, the RunConfig and the vMCP config.valueis used without leading and trailing ASCII white space, the same white space the CRD's\Spattern recognises, must hold more than that white space, and is at most 65536 characters, so both copies in the RunConfig ConfigMap stay well under its 1 MiB limit. A VirtualMCPServer setsspec.instructionsorspec.config.instructions, not both.instructionsmiddleware that sets theinstructionsof successfulinitializeandserver/discoverresults.replacereturns the value.appendandprependjoin it to the server's text with a blank line. When the server sends none, every mode returns the value.initializeandserver/discoverrequests, matched by id, and GETs withLast-Event-ID, which resume a stream that may replay the result; it leaves other GET streams alone. On legacy SSE (transportsse, orstdiowith proxy modesse) it reads the GET event stream, where the result arrives, and leaves POST responses alone.PopulateMiddlewareConfigsfor the operator and proxy runner, andWithMiddlewareFromFlagsforthv run. The operator mapsspec.instructionsinto the RunConfig. vMCP wraps its Modern/Legacy classification with the same middleware, so it covers the SDK's results and the Modern dispatcher'sserver/discover.thv run --instructions-fileand--instructions-mode. The setting is kept across workload upgrades and API edits, andthv exportwrites it into the MCPServer. The API cannot set it yet.Fixes #7279
Type of change
Test plan
task test)task test-e2e)task lint-fix)New tests cover the three modes and value bounds; JSON and event-stream bodies for
initializeandserver/discover; each case the middleware withholds; error, non-2xx and other-method responses passing through; which requests each transport reads, resumed Streamable HTTP GETs included; decoy results and lifetime reading on GET streams; streams that end after a withhold, checked against a real HTTP server; the bounds, treating one write and several alike; 1xx statuses, a repeatedWriteHeader,http.ResponseController, write errors and warn-once; the legacy SSE transport end to end throughhttpsse; the stdio initialize cache, which keeps the backend's result while each handshake gets the text once; authz list filtering with the middleware in the chain; the operator's CRD to RunConfig mapping; the vMCP converter, validator and admission rule; and vMCPinitializeplus bothserver/discoverpaths. The admission rule and value bounds are also checked with envtest (cmd/thv-operator/test-integration/virtualmcp).task operator-generate,task operator-manifests,task crdref-gen,task docsandtask genleave the tree clean, andtask docs-verify,task license-checkandtask sdk-testpass.API Compatibility
v1beta1API, OR theapi-break-allowedlabel is applied and the migration guidance is described above.The new
instructionsfield is optional on all three CRDs. The VirtualMCPServer rule only involves the new fields.crd-schema-checkerreports the three CRDs compatible with v0.69.1.Changes
pkg/mcp/instructions/instructions.goConfigandModetypes, validation, bounds, and the three modespkg/mcp/instructions_middleware.goinitializeandserver/discoverresults, and withhold what they cannot rewritepkg/runner/config.go,config_builder.go,middleware.goRunConfig.Instructions,WithInstructions, factory registration, and placement and transport in both middleware pathscmd/thv/app/run_flags.go--instructions-fileand--instructions-modepkg/workloads/upgrade/applier.go,pkg/api/v1/workload_service.goInstructionsacross upgrades and API editspkg/export/k8s.goInstructionsinto the MCPServercmd/thv-operator/api/v1beta1/*_types.gospec.instructionson MCPServer, MCPRemoteProxy and VirtualMCPServer, and the VirtualMCPServer admission rulecmd/thv-operator/controllers/*_runconfig.gospec.instructionsinto the RunConfigcmd/thv-operator/pkg/vmcpconfig/converter.gospec.instructionsinto the vMCP configpkg/vmcp/config/*.go,pkg/vmcp/cli/serve.go,pkg/vmcp/server/*.gocmd/thv-operator/Taskfile.ymlpkg/mcp/instructionsdocs/middleware.md,docs/arch/02-*.md,docs/arch/05-*.md,docs/arch/10-*.mddocs/operator/crd-api.md,docs/cli,docs/server,sdk/goDoes this introduce a user-facing change?
Yes. Before, clients always received the instructions the server sent. After, when
spec.instructionsis set on an MCPServer, MCPRemoteProxy or VirtualMCPServer, orthv rungets--instructions-file, theinstructionsmember of each successfulinitializeandserver/discoverresult follows the configured mode. Those responses no longer carry the backend'sContent-Length, because the rewrite changes their length.With the setting present, a response the middleware cannot rewrite is withheld:
-32603,internal error) under HTTP 500, with its ownContent-Lengthand the request's id. This covers a compressed or non-UTF-8 body, an ambiguous or non-JSONContent-Type, a body over 1 MiB, a 2xx answer without the result (empty bodies included), and a result that does not decode as one unambiguous message.Each withheld response is logged once at WARN with its cause. A well-behaved server never meets these cases. Nothing changes when the setting is absent.
Special notes for reviewers
server/discoveris covered because the 2026-07-28 revision replacesinitializewith it and its result carriesinstructions. A client that only discovers would otherwise never see the text.protocolVersion,serverInfoorsupportedVersionsunder any spelling a decoder binds, whatever its id. A decoy before the real result changes nothing. The cost is a check of every event's bytes for the life of the stream: events that name none of those members, through escapes and case folding included, pass undecoded, and only the rest is decoded. Data that does not decode is read leniently: it is withheld when a client could read it as such a result, or when it is not valid JSON at all.eventtype, because the go-sdk legacy SSE client dispatches every type as a message. On the stream that answers a POST, only an event without a type or of typemessageends the search, so a result in an event of another type cannot let a later result through unread.replace, the server still reaches the model through its tool descriptions and tool results.mcpcompat(toolhive-core v0.0.62) exposes no way to setServerOptions.Instructions. vMCP produces no instructions today, so every mode returns the configured value there.test/e2e/thv-operatorcase that checks an MCPServer'sinitializeresult if you want one in this PR.Implementation plan
Approved implementation plan
instructionswithmode(replace,append,prepend; defaultappend) andvalue, on every CRD that serves an MCP endpoint, in every served API version.initializeandserver/discoverresults. Follow the tool filter and tools-override precedent: RunConfig field, both middleware paths, JSON and event-stream bodies, the legacy SSE GET stream, fail-closed handling, andthv runflags.spec.instructionsthrough the vMCP config and apply the same three modes to whatever instructions vMCP produces.🤖 Generated with Claude Code