Skip to content

Let operators set the instructions MCP endpoints return - #7280

Merged
jhrozek merged 16 commits into
stacklok:mainfrom
aron-muon:mcp-instructions
Nov 26, 2026
Merged

jhrozek merged 16 commits into
stacklok:mainfrom
aron-muon:mcp-instructions

Conversation

@aron-muon

@aron-muon aron-muon commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MCP clients add a server's instructions to 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.

  • Add an optional instructions field (mode, value) to MCPServer, MCPRemoteProxy and VirtualMCPServer, in both served API versions. The type lives in pkg/mcp/instructions and is shared by the CRDs, the RunConfig and the vMCP config. value is used without leading and trailing ASCII white space, the same white space the CRD's \S pattern 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 sets spec.instructions or spec.config.instructions, not both.
  • Add an instructions middleware that sets the instructions of successful initialize and server/discover results. replace returns the value. append and prepend join it to the server's text with a blank line. When the server sends none, every mode returns the value.
  • The transport decides what the middleware reads. On Streamable HTTP it reads the responses to POSTed initialize and server/discover requests, matched by id, and GETs with Last-Event-ID, which resume a stream that may replay the result; it leaves other GET streams alone. On legacy SSE (transport sse, or stdio with proxy mode sse) it reads the GET event stream, where the result arrives, and leaves POST responses alone.
  • The middleware fails closed, as the tool filter does. A response it reads but cannot rewrite is withheld and answered with a JSON-RPC internal error, so a server cannot keep the text from clients.
  • Wire the middleware inside the MCP parser on both middleware paths: PopulateMiddlewareConfigs for the operator and proxy runner, and WithMiddlewareFromFlags for thv run. The operator maps spec.instructions into the RunConfig. vMCP wraps its Modern/Legacy classification with the same middleware, so it covers the SDK's results and the Modern dispatcher's server/discover.
  • Add thv run --instructions-file and --instructions-mode. The setting is kept across workload upgrades and API edits, and thv export writes it into the MCPServer. The API cannot set it yet.

Fixes #7279

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

New tests cover the three modes and value bounds; JSON and event-stream bodies for initialize and server/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 repeated WriteHeader, http.ResponseController, write errors and warn-once; the legacy SSE transport end to end through httpsse; 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 vMCP initialize plus both server/discover paths. 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 docs and task gen leave the tree clean, and task docs-verify, task license-check and task sdk-test pass.

API Compatibility

  • This PR does not break the v1beta1 API, OR the api-break-allowed label is applied and the migration guidance is described above.

The new instructions field is optional on all three CRDs. The VirtualMCPServer rule only involves the new fields. crd-schema-checker reports the three CRDs compatible with v0.69.1.

Changes

File Change
pkg/mcp/instructions/instructions.go Shared Config and Mode types, validation, bounds, and the three modes
pkg/mcp/instructions_middleware.go Middleware and factory that rewrite initialize and server/discover results, and withhold what they cannot rewrite
pkg/runner/config.go, config_builder.go, middleware.go RunConfig.Instructions, WithInstructions, factory registration, and placement and transport in both middleware paths
cmd/thv/app/run_flags.go --instructions-file and --instructions-mode
pkg/workloads/upgrade/applier.go, pkg/api/v1/workload_service.go Keep Instructions across upgrades and API edits
pkg/export/k8s.go Export Instructions into the MCPServer
cmd/thv-operator/api/v1beta1/*_types.go spec.instructions on MCPServer, MCPRemoteProxy and VirtualMCPServer, and the VirtualMCPServer admission rule
cmd/thv-operator/controllers/*_runconfig.go Map spec.instructions into the RunConfig
cmd/thv-operator/pkg/vmcpconfig/converter.go Promote spec.instructions into the vMCP config
pkg/vmcp/config/*.go, pkg/vmcp/cli/serve.go, pkg/vmcp/server/*.go vMCP config field and validation, plumbing, and the middleware on the MCP endpoint
cmd/thv-operator/Taskfile.yml Generate deepcopy for pkg/mcp/instructions
docs/middleware.md, docs/arch/02-*.md, docs/arch/05-*.md, docs/arch/10-*.md Document the middleware and its place in each chain
CRDs, docs/operator/crd-api.md, docs/cli, docs/server, sdk/go Regenerated

Does this introduce a user-facing change?

Yes. Before, clients always received the instructions the server sent. After, when spec.instructions is set on an MCPServer, MCPRemoteProxy or VirtualMCPServer, or thv run gets --instructions-file, the instructions member of each successful initialize and server/discover result follows the configured mode. Those responses no longer carry the backend's Content-Length, because the rewrite changes their length.

With the setting present, a response the middleware cannot rewrite is withheld:

  • A whole body is answered with a JSON-RPC error (-32603, internal error) under HTTP 500, with its own Content-Length and the request's id. This covers a compressed or non-UTF-8 body, an ambiguous or non-JSON Content-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.
  • On the event stream that answers a POST, an error event takes the place of the event that carried the result. When the stream cannot be read further, because of an event over 1 MiB or a server that ends lines with a bare CR, the error event follows the events already written and the stream ends.
  • On a stream a GET opened, an event that may carry the result but cannot be rewritten becomes an error event when it names an id and is dropped otherwise, and an event over 16 MiB that may name a result member is withheld alone; the stream goes on. An event over 16 MiB that names none is forwarded intact as it arrives, so large tool and resource results still reach clients. An event forwarded in pieces that names a result member only later is cut short with a blank line and withheld alone. A line that clients split differently is decided per event, since every client agrees where an event ends: inside a data value it does no harm, and elsewhere the event is withheld alone if it may name a result member. Only a server that ends lines with a bare CR, which leaves no event end every client agrees on, gets its GET stream ended. A GET whose body cannot be read gets the error and ends.
  • Whenever a response ends this way, the handler's next write returns an error, so it stops and the client sees the end instead of waiting.

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/discover is covered because the 2026-07-28 revision replaces initialize with it and its result carries instructions. A client that only discovers would otherwise never see the text.
  • A stream a GET opened answers no single request, so the middleware reads it for as long as it lasts and rewrites every result that has protocolVersion, serverInfo or supportedVersions under 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.
  • An event stream's leading byte order marks are dropped before lines are read, as clients do, so the first event's type is read the way clients read it.
  • Every event is read whatever its event type, 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 type message ends the search, so a result in an event of another type cannot let a later result through unread.
  • The instructions are guidance for the model, not a sanitiser. With replace, the server still reaches the model through its tool descriptions and tool results.
  • vMCP uses the HTTP middleware rather than an SDK option because mcpcompat (toolhive-core v0.0.62) exposes no way to set ServerOptions.Instructions. vMCP produces no instructions today, so every mode returns the configured value there.
  • The PR is over the 10-file and 400-line guideline. It splits cleanly into the shared type, middleware, runner and CLI, and then the CRD fields, operator mapping and vMCP. I can split it if you prefer.
  • There are no e2e tests yet. I can add a test/e2e/thv-operator case that checks an MCPServer's initialize result if you want one in this PR.

Implementation plan

Approved implementation plan
  • One shared API type, instructions with mode (replace, append, prepend; default append) and value, on every CRD that serves an MCP endpoint, in every served API version.
  • MCPServer and MCPRemoteProxy: the operator maps the field into the RunConfig, and the proxy runner applies it as a middleware that rewrites only successful initialize and server/discover results. 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, and thv run flags.
  • VirtualMCPServer: map spec.instructions through the vMCP config and apply the same three modes to whatever instructions vMCP produces.
  • Check that the authz middleware and the stdio initialize cache still behave with the new middleware in the chain.

🤖 Generated with Claude Code

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

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.97913% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.52%. Comparing base (fc81f63) to head (962af7e).

Files with missing lines Patch % Lines
pkg/mcp/instructions_middleware.go 93.08% 32 Missing ⚠️
pkg/runner/middleware.go 85.71% 2 Missing ⚠️
pkg/runner/config_builder.go 91.66% 1 Missing ⚠️
pkg/vmcp/cli/serve.go 0.00% 1 Missing ⚠️
pkg/vmcp/server/server.go 83.33% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

aron-muon and others added 2 commits November 24, 2026 18:03
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 jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, BuildFullRunConfig rebuilds the RunConfig from the request, and instructions set with thv run --instructions-file get dropped. Change an env var in Studio and after the restart clients no longer see the policy text, with nothing to tell anyone. Could persisted.Instructions be carried over via WithInstructions (before WithMiddlewareFromFlags), 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.go doesn't copy Instructions into the exported MCPServer, so thv export drops it.
  • docs/arch/02-core-concepts.md has a list of middleware types that's missing instructions.
  • Some untested paths in the middleware: 1xx before the final status, WriteHeader called twice, Unwrap/http.ResponseController, an event stream with Content-Encoding, an empty 2xx body (the "no result" warning in finish), and warn-once.

Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions/instructions.go Resolved
Comment thread pkg/vmcp/config/config.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread docs/middleware.md Resolved
Comment thread pkg/runner/config.go Resolved
aron-muon and others added 6 commits November 25, 2026 18:26
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]>
@aron-muon

Copy link
Copy Markdown
Contributor Author

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:

  • BuildFullRunConfig now carries persisted.Instructions over with WithInstructions before WithMiddlewareFromFlags, with a "not supported via API yet" note, and thv export copies Instructions into the MCPServer (24092ac).
  • docs/arch/02-core-concepts.md lists instructions with the other middleware types (eea1b5e).
  • The middleware tests now cover a 1xx before the final status, a repeated WriteHeader, Unwrap through http.ResponseController, event streams with Content-Encoding on both transports, empty 2xx bodies, and warn-once (cffefd0).

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 ChrisJBurns left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the inline comments.

Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
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 ChrisJBurns left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See the inline comments.

Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
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 jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions_middleware.go Resolved
Comment thread pkg/mcp/instructions/instructions.go Resolved
Comment thread pkg/vmcp/server/server.go Resolved
aron-muon and others added 4 commits November 26, 2026 18:40
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]>
@aron-muon

Copy link
Copy Markdown
Contributor Author

Merged origin/main in cdcab4f. The conflicts were the MCPServerSpec comment next to instructions and the vMCP pipeline table, and crd-api.md is regenerated. The nit is fixed in 962af7e: TestBuildFullRunConfig_KeepsPersistedInstructions now follows TestBuildFullRunConfig_NoOtelConfigLeavesTelemetryNil.

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhrozek
jhrozek merged commit 4b9f678 into stacklok:main Nov 26, 2026
92 of 93 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let operators set the instructions an MCP endpoint returns

3 participants