Skip to content

[TT-18784] Remote MCP tool overrides: merge the feature branch (Gateway) - #8997

Open
andrei-tyk wants to merge 4 commits into
masterfrom
TT-18784-mcp-override-feature-branch
Open

andrei-tyk wants to merge 4 commits into
masterfrom
TT-18784-mcp-override-feature-branch

Conversation

@andrei-tyk

@andrei-tyk andrei-tyk commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Merges the remote MCP tool overrides feature (TT-18784) into master. Platform administrators can override the names, descriptions and annotations (title, read-only, destructive, idempotent, open-world hints) of tools exposed by a remote MCP proxy without changing the upstream MCP server. Policies match the name the client sees, as for API-to-MCP.

Each change below was reviewed and squash-merged into TT-18784-mcp-override-feature-branch as its own PR. This PR carries those 4 squash commits.

Story PR
TT-18788 Tool annotation overrides #8900
TT-18787 Tool name and description overrides #8902, #8930, #8931

Cross-repo

  • Dashboard: TykTechnologies/tyk-analytics feature-branch PR (same branch name) adds persistence, the save-time catalogue check and the end-to-end tests. Its MCP override API tests need this Gateway code.
  • Dashboard UI: TykTechnologies/tyk-analytics-ui feature-branch PR (same branch name).

Notes

🤖 Generated with Claude Code

Ticket Details

TT-18784
Status Open
Summary MCP tool enrichment

Generated at: 2026-11-26 15:23:33

andrei-tyk and others added 4 commits November 26, 2026 17:19
## Description
Remote MCP proxies can now select an upstream tool by name in
`x-tyk-mcp-server` and override its annotations. Before this change,
`tools/list` passed the upstream's tool list straight through.

- **Config:** `x-tyk-mcp-server.primitives[].source.toolName` is a new
selector, allowed only on remote MCP proxies, with optional `name`,
`description` and `annotations` (`title`, `readOnlyHint`,
`destructiveHint`, `idempotentHint`, `openWorldHint`). REST selectors
stay limited to `tyk://` adapters. `parameters` and `allow` are rejected
on remote proxies.
- **Validation:**
- Tool names: ASCII letters, digits, `_` `-` `.`; at most 128
characters.
  - Duplicate final names and duplicate sources are rejected.
  - Annotation hints must be booleans.
  - Swaps and reuse of a freed name are allowed.
- **Upstream catalogue check:**
- When the API loads, the Gateway applies the overrides immediately. In
the background it fetches the upstream `tools/list` (all pages, 10 s
timeout) and logs a Warning for each override whose name an untouched
upstream tool already has, and for each missing source tool. An
unreachable upstream gets a "could not list" Warning. Loading never
blocks, and a fresh gateway behaves the same as a reload.
- The save-time reject of such a collision lives in the Dashboard
(`oas.CheckRemoteMCPToolCatalogue`).
- The pure check is `oas.CheckRemoteMCPToolCatalogue` and the fetcher is
`apidef/mcp/catalogue.FetchToolNames`, so the Dashboard can reuse them.
- **Runtime (this PR):** annotations are merged field by field into
`tools/list` on both the JSON and SSE paths, even without ACL rules:
  - an explicit `false` replaces the upstream value;
  - unset fields inherit;
  - only `annotations.title` changes, never the top-level `title`;
  - unknown fields and `nextCursor` are kept;
  - a tool whose source is missing upstream is omitted, with a warning.
- The response cache is bypassed for `tools/list` and `tools/call` on
APIs with overrides.
- **Unchanged:** annotations never affect access control or rate limits,
and REST-as-MCP / API-to-MCP behaviour stays the same.

Name and description are validated here but **applied in the stacked
follow-up PR for TT-18787, #8902**. This PR should not be released
without it.

### Review follow-up (2026-11-17)
After a client-focused review, two fixes were added as new commits:
- **Compressed upstream responses.**
- gzip and deflate `tools/list`, initialize and discovery responses,
JSON or SSE, are now decoded before they are rewritten or filtered.
Before, they passed through unchanged: overrides and access-rule list
filtering were skipped, and gzipped SSE was corrupted.
- On requests whose response may be edited, the outbound
`Accept-Encoding` is narrowed to codings the Gateway can decode, so br
and zstd can't bypass the rewrite.
- Decoded size is capped at `max_response_body_size`, or at 32 MiB when
that setting is 0.
- Edited bodies are sent uncompressed without `ETag` or `Last-Modified`.
Unedited bodies pass through byte for byte.
- **Overrides apply at load.** The view is admitted straight away,
rather than after the catalogue check. A fresh gateway no longer serves
raw upstream names when the check finds a collision, and there is no
longer a window without overrides.
- `BenchmarkMCPListFilter` B/op and allocs/op are unchanged, and ns/op
is within 1%.

## Related Issue
- [TT-18788](https://tyktech.atlassian.net/browse/TT-18788): override
tool annotations on a remote MCP proxy (epic
[TT-18784](https://tyktech.atlassian.net/browse/TT-18784))
- Foundation for
[TT-18787](https://tyktech.atlassian.net/browse/TT-18787) (name and
description overrides)
- Test upstream:
[TykTechnologies/tyk-mock-mcp-server#13](TykTechnologies/tyk-mock-mcp-server#13)

## Motivation and Context
Platform administrators need to correct or add behavioural hints on
tools from MCP servers they don't own, so that AI clients know when to
ask a person for confirmation. Product decisions applied:
- the Jira acceptance criteria are the contract (swaps allowed, warn and
omit on drift, no safety checks on annotations);
- "title" means `annotations.title`;
- an omitted field inherits, and an explicit `false` is kept.

## How This Has Been Tested
**Before (master `8d8e1f804`):** the remote-proxy config is rejected by
the schema:
```
ValidateMCPObject(remote proxy, source.toolName=delete_repo, destructiveHint=true)
=> x-tyk-mcp-server.primitives.0.source: Additional property toolName is not allowed
```

**After (this branch):** acceptance criteria → tests (JSON and SSE
through a real gateway with an httptest MCP upstream, unless marked
unit):

| AC | Test |
|---|---|
| Mark a tool as destructive |
`TestRemoteMCPToolView_ToolsListAnnotations/{json,sse}/…delete_repo_without_upstream_annotations_marked_destructive`
|
| Explicit value replaces upstream / explicit false applied |
`…/{json,sse}/…idempotentHint_and_openWorldHint_true_overridden_with_false`
|
| Unset fields keep the upstream value |
`…/{json,sse}/…only_annotations.title_changes;_upstream_hints_and_top-level_title_kept`
|
| Override a renamed tool |
`TestView_RewriteToolsList_AnnotationsOfARenamedTool` (unit). Gateway
proof comes with the rename PR. |
| Tools without an override unchanged |
`…/{json,sse}/…tool_without_override_unchanged…`,
`TestRemoteMCPToolView_NoViewLeavesToolsListUntouched` |
| Invalid annotation value |
`TestMCPAPI_RejectsNonBooleanToolAnnotationHint` (POST/PUT `/tyk/mcps` →
400 `…annotations.destructiveHint: Invalid type. Expected: boolean,
given: string`) |
| Override for a tool the upstream no longer has |
`TestRemoteMCPToolView_MissingSourceToolIsOmittedWithAWarning`,
`TestRemoteMCPToolView_CatalogueCheckOnLoad/admits_the_view…warns_about_missing_sources`
|
| Annotations do not change enforcement |
`TestRemoteMCPToolView_AnnotationsDoNotChangeEnforcement` (403; the
upstream is never called) |
| TT-18787 config validation (invalid name, 129 chars, duplicate,
collision with an upstream tool, swap) |
`TestValidateRemoteMCPToolOverrides/*`,
`TestCheckRemoteMCPToolCatalogue/*`,
`TestRemoteMCPToolView_CatalogueCheckOnLoad/*collision*` |

Also covered:
- the catalogue check does not follow redirects and does not leak the
upstream credential;
- loading is not blocked;
- a reload while a check is still running cancels the stale check;
- the response cache bypass, tested through the gateway.

Runs (local, Go 1.25):
- `go test -count=1 -v` over the AC tests in `apidef/oas`, `apidef/mcp`,
`apidef/mcp/catalogue`, `internal/mcp/tooloverride` and `gateway` (with
`-race`): **93 PASS, 0 FAIL**.
- `go test -count=1 -v ./gateway -run
'MCP|Mcp|JSONRPC|ListFilter|SSE|Cache'`: **1008 PASS, 0 FAIL**. The 10
skips are existing unconditional skips in `gateway_test.go`.
- `go test -race -count=50 -run TestRemoteMCPToolView ./gateway/`:
**1700 PASS, 0 data races**.
- Benchmark of the list rewrite (50 tools, 10 overrides): about 112 KB
and 669 allocs per op. APIs without overrides pay one atomic load.
- The full `./gateway` suite was not completed locally (40-minute
timeout; failures that also occur on master). CI is authoritative.

**Demo:** an end-to-end recording through a Dashboard and Gateway stack
with the mock MCP upstream will be added as a comment, once the stacked
rename PR and the Dashboard tests are in place.

Known limits:
- The catalogue check uses only the upstream `TargetURL` plus static
basic auth; the stacked PR #8930 makes it reach the upstream like the
proxy does. APIs that use load balancing or service discovery get the
"could not list" warning.
- Request-time missing-source warnings fire only for single-page lists.
The load-time check covers lists with several pages.

## Types of changes
- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Refactoring or add test (improvements in base code or adds test
coverage to functionality)

## Checklist
- [ ] I ensured that the documentation is up to date. Docs for
remote-proxy overrides are to follow with TT-18787.
- [x] I explained why this PR updates go.mod in detail with reasoning
why it's required (no go.mod change)
- [ ] I would like a code coverage CI quality gate exception and have
explained why

🤖 Generated with [Claude Code](https://claude.com/claude-code)


[TT-18788]:
https://tyktech.atlassian.net/browse/TT-18788?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ









<!---TykTechnologies/jira-linter starts here-->

### Ticket Details

<details>
<summary>
<a href="https://tyktech.atlassian.net/browse/TT-18788" title="TT-18788"
target="_blank">TT-18788</a>
</summary>

|         |    |
|---------|----|
| Status  | In Code Review |
| Summary | Override tool annotations on a remote MCP proxy |

Generated at: 2026-11-26 11:38:19

</details>

<!---TykTechnologies/jira-linter ends here-->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…#8902)

## Description
Remote MCP proxies can now rename upstream tools and reword their
descriptions with `x-tyk-mcp-server` overrides selected by
`source.toolName`. Calls are mapped back to the upstream's real tool
name. This PR is stacked on #8900, which adds the shared config,
validation, the upstream catalogue check and annotation overrides.

- **Discovery (`tools/list`, JSON and SSE)**
  - `name` and `description` are replaced field by field.
- `inputSchema`, the top-level `title`, `_meta` and unknown fields are
kept.
  - A renamed tool's original name is no longer listed.
- Swaps work: `remove_repo`→`delete_repo` together with
`update_repo`→`remove_repo`.
- ACL list filtering runs after the rewrite, so rules match exposed
names.
- **Invocation**
- Access rights, allow-lists, per-tool rate limits and analytics all key
on the exposed name.
- At final dispatch (`MCPVEMContinuationMiddleware`, after every check),
the gateway rewrites `params.name` to the upstream name. Each `Mcp-Name`
header value is re-encoded to match, using the client's own encoding
(plain or `=?base64?…?=`).
  - Arguments, `_meta`, id and the result are untouched.
- **Original name rejected**
- A call to a tool that was renamed away, and whose name isn't bound by
another override, returns JSON-RPC `-32602 unknown tool "<name>"` (HTTP
400, the gateway's existing mapping). The upstream never sees it.
  - Unauthenticated callers get 401 first.
- **Upstream drift**
- If an override's source disappears, the tool is omitted and a warning
names the missing source.
- If the upstream adds its own tool with an overridden name, the
explicit override wins. The upstream tool is hidden and a warning names
it, so an upstream change can't silently redirect calls.
  - Warnings are rate-limited per tool.

### Review follow-up (2026-11-17)
- This PR now merges the #8900 fixes for compressed responses and for
applying overrides at load.
- **New tests in `gateway/mcp_remote_tool_view_names_load_test.go`:**
- On a fresh load where the upstream also has `open_issue`, only the
override is listed, and a call to `open_issue` reaches `create_issue`.
This holds before the catalogue check finishes, after it and on a
reload. Before the fix, a fresh gateway listed and called the upstream's
own `open_issue`.
- Renames work through a gzip-compressing upstream (JSON and SSE) and
for a br-preferring client.
- **Collision warning text:** "the override wins and the upstream tool
is hidden".
- **Stacked follow-ups:** #8930 (the catalogue check reaches the
upstream like the proxy) and #8931 (warnings for `mcpTools` entries that
a rename changed).

## Related Issue
- [TT-18787](https://tyktech.atlassian.net/browse/TT-18787): override
tool names and descriptions on a remote MCP proxy (epic
[TT-18784](https://tyktech.atlassian.net/browse/TT-18784)). It also
completes TT-18788's "override a renamed tool" criterion.
- Base: #8900 (TT-18788). Test upstream:
[TykTechnologies/tyk-mock-mcp-server#13](TykTechnologies/tyk-mock-mcp-server#13).

## Motivation and Context
Administrators need clear, consistent tool names and descriptions for AI
agents, even when the MCP server belongs to someone else.

Per the story:
- policies match the name the client sees;
- an administrator who renames a tool must update the rules that use its
old name, since no automatic migration happens;
- argument renaming is out of scope.

## How This Has Been Tested
**Before** (base #8900, with the override configured): the rename tests
fail, so the upstream name leaks through and the call is not translated.
```
--- FAIL: TestRemoteMCPToolView_ToolsListRenamesAndDescriptions/{json,sse}/…   (create_issue still listed, no new description)
--- FAIL: TestRemoteMCPToolView_CallToAnExposedNameReachesTheUpstreamTool/…
    expected: "create_issue"   actual: "open_issue"      (upstream received the exposed name)
```

**After** (this branch, through a real gateway and an httptest MCP
upstream that records what it received):

| Acceptance criterion | Test |
|---|---|
| Override name and description accepted and saved |
`TestMCPAPI_RemoteToolNameAndDescriptionOverrideRoundTrip` |
| Invalid name, 129 characters, duplicate, collision with an upstream
tool | PR A validation and catalogue tests (re-run green) |
| Tools swap names |
`TestRemoteMCPToolView_ToolsListAfterASwap/{json,sse}` |
| Overridden name and description listed; tools without an override
unchanged; input schema unchanged |
`TestRemoteMCPToolView_ToolsListRenamesAndDescriptions/{json,sse}/*` |
| Call by overridden name reaches the upstream tool |
`TestRemoteMCPToolView_CallToAnExposedNameReachesTheUpstreamTool/{json,sse}/{without,plain,base64}_Mcp-Name`,
`/modern_request_with_mirrored_headers` |
| Call by the original name is rejected |
`TestRemoteMCPToolView_CallToARenamedAwayToolIsUnknown/*` (the upstream
receives nothing) |
| Rule matches the exposed name; a rule on the old name no longer
applies; the rule follows the name after a swap |
`TestRemoteMCPToolView_AccessRulesApplyToExposedNames/*` (list),
`TestRemoteMCPToolView_CallsAuthorisedOnExposedNames/*` (call) |
| Per-tool rate limit matches the exposed name |
`TestRemoteMCPToolView_CallsAuthorisedOnExposedNames/…` (5 × 200, then
429; the upstream receives 5 × `create_issue`) |
| Override for a tool the upstream no longer has |
`TestRemoteMCPToolView_RenamedSourceMissingUpstream/{json,sse}` |
| Upstream adds a tool that collides with an override |
`TestRemoteMCPToolView_UpstreamToolNamedLikeAnOverrideIsHidden/{json,sse}`,
`TestRemoteMCPToolView_CallAfterUpstreamDrift/*` |
| TT-18788: override a renamed tool |
`TestRemoteMCPToolView_ToolsListRenamesAndDescriptions/{json,sse}/renamed
tool carries the idempotentHint override…` |
| Hardening |
`TestRemoteMCPToolView_McpNameHeaderFollowsTheDispatchedTool`,
`TestRemoteMCPToolView_UnknownToolWithoutAnIDIsRejected` |

A reviewer also probed these bypass attempts through the gateway, and
none reached a renamed-away tool:
- unicode-escaped names;
- duplicate `name` keys;
- batches;
- notifications;
- a mismatched legacy `Mcp-Name` header;
- a mismatch between the parsed state and the request body.

Local runs:
- AC tests at HEAD: **128 PASS, 0 FAIL, 0 SKIP**.
- `go test -count=1 -v ./gateway -run
'MCP|Mcp|JSONRPC|ListFilter|SSE|Cache'`: **1070 PASS, 0 FAIL**. The 10
skips are existing unconditional `TestCache*` skips. One earlier run hit
a flake in `TestMCPAnalytics_Initialize_NoPrimitiveFields` (shared
upstream; it doesn't reach this code), which passed 10/10 on rerun.
- REST-as-MCP and API-to-MCP regression
(`RESTAsMCP|Synthetic|Paired|Pairing|ToolView|SDKNameBridge|MCPAdapter`):
**197 PASS, 0 FAIL**.
- `go test -race -count=20 -run TestRemoteMCPToolView ./gateway/`: ok,
no data races.
- Benchmark, 50 tools with 10 renamed: about 395 µs, 115 KB and 709
allocs per op, roughly 4 allocs per renamed tool. APIs without overrides
are unaffected.

**Demo:** an end-to-end recording through Dashboard + Gateway + mock MCP
upstream will be added as a comment. It covers the list before and
after, a translated call, a rejected original name, and drift.

Behaviour notes for reviewers:
- **Unknown tool returns HTTP 400.** Official MCP SDK clients surface
any non-2xx response as a transport error. This matches how the gateway
already handles ACL denials (403).
- **Unknown-tool calls consume rate limit and quota**, because the check
runs after them, which avoids revealing tool names to unauthenticated
callers.
- **Detailed request recording logs the translated upstream name in the
raw body**, while the MCP analytics fields keep the exposed name.
- **The `Mcp-Name` header is overwritten on legacy requests.** On an API
with overrides, the header is always rewritten to the name of the tool
actually dispatched.

## Types of changes
- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Refactoring or add test (improvements in base code or adds test
coverage to functionality)

## Checklist
- [ ] I ensured that the documentation is up to date (docs ticket to
follow)
- [x] I explained why this PR updates go.mod in detail with reasoning
why it's required (no go.mod change)
- [ ] I would like a code coverage CI quality gate exception and have
explained why

🤖 Generated with [Claude Code](https://claude.com/claude-code)


[TT-18787]:
https://tyktech.atlassian.net/browse/TT-18787?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ










<!---TykTechnologies/jira-linter starts here-->

### Ticket Details

<details>
<summary>
<a href="https://tyktech.atlassian.net/browse/TT-18787" title="TT-18787"
target="_blank">TT-18787</a>
</summary>

|         |    |
|---------|----|
| Status  | In Code Review |
| Summary | Override tool names and descriptions on a remote MCP proxy |

Generated at: 2026-11-25 17:17:26

</details>

<!---TykTechnologies/jira-linter ends here-->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…verrides (#8930)

## Description

When the Gateway loads a remote MCP proxy that has tool overrides, it
fetches the upstream tool list in the background to log warnings about
collisions and missing source tools. Before this change, that fetch sent
only static upstream basic auth, over a bare transport. It now reaches
the upstream the way the proxy does:

- **Transport:** it uses the proxy's own transport (`httpTransport`).
That covers the API's proxy URL (or the `HTTP(S)_PROXY` environment
proxy), TLS versions and ciphers, `SSLInsecureSkipVerify`, certificate
pinning, the DNS cache, HTTP/2 and h2c. h2c targets are scheme-marked as
in `WrappedServeHTTP`.
- **Upstream mTLS:** the upstream mTLS client certificate is sent, and
the common-name check runs when the request goes through a proxy.
- **Headers:** the API's static global request headers are sent. Values
with `$tyk_context.` or `$tyk_meta.` placeholders are skipped, because
there is no client request to resolve them from; secret references are
resolved.
- **Upstream auth:** the proxy's upstream basic auth and upstream OAuth
(client credentials and password) are sent through
`core.GetUpstreamAuth`. The OAuth token goes into the same Redis cache
the proxy uses. Upstream auth is skipped when the MCP OAuth broker is
enabled, as on the proxy.
- **Unchanged:** redirects are still not followed, and the 10s timeout
and response size bounds still apply.

**Behaviour changes to note:**
- Upstream auth is an Enterprise feature. On CE builds the check now
sends no upstream basic auth, matching the proxy, which never sent it
there. Such upstreams log the existing "could not list" warning. Since
the check only logs, nothing else changes, and the Enterprise-only error
isn't logged a second time.
- The check now honours the environment proxy, as the proxy does.
Before, it forced the proxy off.

## Related Issue

[TT-18787](https://tyktech.atlassian.net/browse/TT-18787), epic
TT-18784. This is a follow-up from the client-focused review.

**Stack:** this PR is based on #8902 (`TT-18787-remote-mcp-tool-names`),
which is based on #8900. Next: #8931 (renamed-tool warnings).

## Motivation and Context

Most real remote MCP servers, GitHub's for example, need a bearer token
or OAuth. With only basic auth, the load-time check got a 401 and logged
"could not list" on every reload, so admins never saw the collision and
missing-tool warnings.

## How This Has Been Tested

- New untagged tests in
`gateway/mcp_remote_catalogue_transport_test.go`:
  - global headers are sent, and placeholder values are not
  - the mTLS client certificate is presented
  - `SSLInsecureSkipVerify` on and off
  - the API proxy URL is used
  - h2c upstreams are listed over HTTP/2
- Tests tagged `ee || dev` in
`gateway/mcp_remote_catalogue_upstream_auth_test.go`:
  - basic auth
  - redirects are not followed
  - OAuth client credentials, with the default and a custom header
  - OAuth password
- a failing token endpoint gives the "could not list" warning and never
calls the upstream
- A CE-only test (`!ee && !dev`) checks that no upstream auth is sent
and the Enterprise-only error isn't repeated.
- Gateway `-run
'MCP|Mcp|ToolView|ListFilter|SSE|UpstreamOAuth|UpstreamBasicAuth'`:
  - default tags: 335 top-level / 872 total pass, 0 fail
  - `-tags "goplugin dev"`: 336 / 879 pass, 0 fail
- `./internal/mcp/... ./apidef/mcp/... ./apidef/oas/...`: all pass.
- A fresh-context reviewer accepted it.

## Types of changes

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Refactoring or add test (improvements in base code or adds test
coverage to functionality)

## Checklist

- [x] I ensured that the documentation is up to date
- [ ] I explained why this PR updates go.mod in detail with reasoning
why it's required
- [ ] I would like a code coverage CI quality gate exception and have
explained why

🤖 Generated with [Claude Code](https://claude.com/claude-code)


[TT-18787]:
https://tyktech.atlassian.net/browse/TT-18787?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ






<!---TykTechnologies/jira-linter starts here-->

### Ticket Details

<details>
<summary>
<a href="https://tyktech.atlassian.net/browse/TT-18787" title="TT-18787"
target="_blank">TT-18787</a>
</summary>

|         |    |
|---------|----|
| Status  | In Code Review |
| Summary | Override tool names and descriptions on a remote MCP proxy |

Generated at: 2026-11-25 17:18:34

</details>

<!---TykTechnologies/jira-linter ends here-->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…8931)

## Description

When the Gateway loads a remote MCP proxy, it now logs a Warning for
each `middleware.mcpTools` entry whose tool a rename changed. Access
rules, rate limits and `mcpTools` follow the exposed tool name, so these
entries quietly change what they cover.

- **Renamed away** (the name is no longer exposed): the Warning says the
setting no longer applies and names the exposed name to use instead. Log
fields: `setting`, `tool`, `exposed_name`.
- **Taken over** (a swap or chain makes the name expose a different
upstream tool): the Warning says the setting now applies to upstream
tool X. Log fields: `setting`, `tool`, `upstream_tool`.
- **Not reported:**
  - wildcard keys
  - names that only appear as new exposed names
- **Enforcement is unchanged.** A test shows that blocking
`create_issue` does not block `open_issue`.
- **Where else this is checked:** policies and keys live outside the API
definition, so the Gateway can't check them at load. The Dashboard
reports both on save (TykTechnologies/tyk-analytics#6513), using the
same rule.

## Related Issue

[TT-18787](https://tyktech.atlassian.net/browse/TT-18787), epic
TT-18784. This is a follow-up from the client-focused review.

**Stack:** this PR is based on #8930, which is based on #8902 and #8900.

## Motivation and Context

- A per-tool block or rate limit on `delete_repo` stops applying once
the tool is renamed.
- After a swap, it applies to a different upstream tool.
- Tyk OSS and GitOps users who load definitions straight into the
Gateway now get a warning about this.

## How This Has Been Tested

- New `tooloverride` methods, with unit tests:
- `View.RenamedAway`, tested in
`internal/mcp/tooloverride/view_renamed_test.go`
- `View.NameTakenBy`, tested by `TestView_NameTakenBy`, covering a swap,
a chain and a plain rename
- `gateway/mcp_remote_tool_view_renamed_settings_test.go`:
  - a rename, a swap (both entries reported) and a chain
  - wildcard keys are skipped
  - enforcement is unchanged
- Gateway `-run
'MCP|Mcp|ToolView|ListFilter|SSE|UpstreamOAuth|UpstreamBasicAuth'`:
  - default tags: 336 / 877 pass, 0 fail
  - `-tags "goplugin dev"`: 337 / 884 pass, 0 fail
- A fresh-context reviewer accepted it.

## Types of changes

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Refactoring or add test (improvements in base code or adds test
coverage to functionality)

## Checklist

- [x] I ensured that the documentation is up to date
- [ ] I explained why this PR updates go.mod in detail with reasoning
why it's required
- [ ] I would like a code coverage CI quality gate exception and have
explained why

🤖 Generated with [Claude Code](https://claude.com/claude-code)


[TT-18787]:
https://tyktech.atlassian.net/browse/TT-18787?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ






<!---TykTechnologies/jira-linter starts here-->

### Ticket Details

<details>
<summary>
<a href="https://tyktech.atlassian.net/browse/TT-18787" title="TT-18787"
target="_blank">TT-18787</a>
</summary>

|         |    |
|---------|----|
| Status  | In Code Review |
| Summary | Override tool names and descriptions on a remote MCP proxy |

Generated at: 2026-11-25 17:19:27

</details>

<!---TykTechnologies/jira-linter ends here-->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@sentinelone-cnapp-eu1

Copy link
Copy Markdown

SentinelOne CNS Hardcoded Secret Detector
✅ Congratulations, your code is safe

SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes.

@github-actions

Copy link
Copy Markdown
Contributor

📚 Documentation preview

This PR changes generated documentation (component: gateway).

cc @TykTechnologies/pms — advisory review requested; this does not block merging.

Rendered docs diff
diff -ruN out-base/gateway-config.mdx out-head/gateway-config.mdx
--- out-base/gateway-config.mdx	2026-11-26 15:23:51.123319110 +0000
+++ out-head/gateway-config.mdx	2026-11-26 15:23:52.462491418 +0000
@@ -3157,12 +3157,3 @@
 A token with no iss claim is matched by key ID (kid) alone.
 It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
 
-### allow_unsafe_websocket_origin
-ENV: <b>TYK_GW_ALLOWUNSAFEWEBSOCKETORIGIN</b><br />
-Type: `bool`<br />
-
-AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
-It exists for compatibility with browser clients on other origins that connected before the check was added.
-Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
-To allow a browser client, add its origin to the API's CORS allowed origins instead.
-
diff -ruN out-base/x-tyk-gateway.mdx out-head/x-tyk-gateway.mdx
--- out-base/x-tyk-gateway.mdx	2026-11-26 15:23:45.350496120 +0000
+++ out-head/x-tyk-gateway.mdx	2026-11-26 15:23:45.408567349 +0000
@@ -3392,6 +3392,17 @@
 
 Type defined as `RateLimit`, see [RateLimit](#ratelimit) definition.
 
+### **RemoteMCPToolCollision**
+
+RemoteMCPToolCollision is an override whose final name is also the name of
+an upstream tool that has no override of its own.
+
+**Field: `Name` (`string`)**
+Name is the name both tools would be exposed under.
+
+**Field: `Source` (`string`)**
+Source is the upstream tool the override renames to Name.
+
 ### **RequestSizeLimit**
 
 RequestSizeLimit limits the maximum allowed size of the request body in bytes.
@@ -3627,6 +3638,10 @@
 **Field: `method` (`string`)**
 Method selects a source REST operation by HTTP method.
 
+**Field: `toolName` (`string`)**
+ToolName selects an upstream tool by name on a remote MCP proxy. It is
+mutually exclusive with the REST selectors above.
+
 ### **URLRewrite**
 
 URLRewrite configures URL rewriting.

@probelabs

probelabs Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces a new feature allowing administrators to override the properties of tools exposed by a remote MCP (Meta-Conversation Protocol) proxy. This enables customization of tool names, descriptions, and annotations (like title, readOnlyHint, destructiveHint) directly within the Tyk Gateway, without needing to modify the upstream MCP server.

Key changes include:

  • A new source.toolName selector in the x-tyk-mcp-server OAS extension to target specific upstream tools for overrides.
  • Upon API load, the Gateway now performs a background check against the upstream tool catalogue to validate the configured overrides. It logs warnings for potential issues, such as name collisions or overrides targeting non-existent tools.
  • The Gateway intercepts and rewrites tools/list responses on-the-fly to apply the configured overrides before sending them to the client.
  • For tools/call requests, the Gateway translates the public-facing (overridden) tool name back to its original upstream name before proxying the request.
  • The implementation correctly handles complexities such as upstream authentication (Basic Auth, OAuth), mTLS, and compressed response bodies (gzip, deflate).
  • Security policies, such as access rules and rate limits, are applied to the exposed (overridden) tool names, ensuring consistent behavior from the client's perspective.

Files Changed Analysis

The changes are substantial, with 4639 additions and 12 deletions across 30 files. The majority of the changes involve adding new files for the core logic and extensive testing.

  • New Core Logic:

    • apidef/mcp/catalogue/: A new package to fetch the tool catalogue from a remote MCP server.
    • apidef/oas/mcp_remote_*.go: Files for validating and inspecting remote tool overrides and checking for collisions.
    • gateway/mcp_remote_tool_view.go: The central implementation in the Gateway, responsible for loading the override configuration, rewriting tools/list responses, and translating tools/call requests.
    • gateway/mcp_remote_catalogue_upstream.go: Manages the HTTP client for fetching the upstream catalogue, respecting the API's transport configuration (auth, mTLS, proxy URL).
    • gateway/mcp_response_decoding.go: Provides functionality to decompress upstream responses (gzip, deflate) so they can be rewritten.
  • New Tests: An extensive suite of tests has been added across more than a dozen new _test.go files, covering the full lifecycle of the feature, including API interactions, call dispatching, response rewriting, and handling of various upstream configurations.

  • Modifications:

    • apidef/mcp/schema/x-tyk-mcp-server.json: The schema is updated to support the new toolName selector.
    • apidef/oas/mcp_server.go: The configuration struct TykMCPServerSource is updated to include ToolName.
    • gateway/api_loader.go: The API loading process now includes a call to loadRemoteMCPToolView to initialize the feature.
    • gateway/model_apispec.go: The APISpec struct is extended to hold the compiled tool override view and state for the background validation check.

Architecture & Impact Assessment

This PR accomplishes the goal of allowing Tyk to serve as a customizable proxy for remote MCP services. It decouples the client-facing tool schema from the upstream implementation.

Key Technical Changes

  1. Configuration-driven Rewriting: The feature is driven by declarative configuration within the OAS API Definition's x-tyk-mcp-server extension.
  2. Asynchronous Validation: On API load, a background goroutine fetches the complete tool catalogue from the upstream server. This validation process does not block API loading. It compares the live catalogue with the configured overrides and logs warnings for any discrepancies (e.g., an override for a tool that doesn't exist, or an override that creates a name collision with another existing tool).
  3. In-Flight Request/Response Modification: The Gateway's MCP proxy logic is enhanced to intercept tools/list responses and tools/call requests. It performs on-the-fly JSON manipulation to apply the overrides, ensuring the client and upstream server see the tool names they expect.

Affected System Components

  • Gateway API Loader: Now responsible for initializing the MCP tool view and triggering the background catalogue check.
  • Gateway MCP Proxy: The core request/response flow for MCP APIs is modified to include the rewriting and translation logic.
  • API Definition & Validation: The schema and validation for OAS-based APIs are updated to recognize and validate the new override configuration.

Component Interaction Diagram

sequenceDiagram
    participant Client
    participant Tyk Gateway
    participant Upstream MCP Server

    alt On API Load
        Tyk Gateway->>Tyk Gateway: Compile overrides from API definition
        Tyk Gateway-)+Upstream MCP Server: (async) Fetch tool catalogue
        Upstream MCP Server--)-Tyk Gateway: Return full tool list
        Tyk Gateway->>Tyk Gateway: Validate overrides and log warnings
    end

    alt tools/list flow
        Client->>+Tyk Gateway: POST /mcp (tools/list)
        Tyk Gateway->>+Upstream MCP Server: Forward tools/list request
        Upstream MCP Server-->>-Tyk Gateway: 200 OK (Response with original tools)
        Tyk Gateway->>Tyk Gateway: Rewrite response body with overrides
        Tyk Gateway-->>-Client: 200 OK (Response with overridden tools)
    end

    alt tools/call flow
        Client->>+Tyk Gateway: POST /mcp (tools/call, name="overridden_name")
        Tyk Gateway->>Tyk Gateway: Translate "overridden_name" to "original_name" in request body
        Tyk Gateway->>+Upstream MCP Server: Forward tools/call with original name
        Upstream MCP Server-->>-Tyk Gateway: 200 OK (Result)
        Tyk Gateway-->>-Client: 200 OK (Forward result)
    end
Loading

Scope Discovery & Context Expansion

This feature extends beyond simple proxying, adding a transformation layer specific to the MCP protocol. The impact spans several areas:

  • Security & Policy Enforcement: Access rules and rate limits defined in the API are applied to the exposed tool names. The implementation correctly handles this, ensuring that policies are enforced as administrators would expect based on the client-facing configuration.
  • Observability: Analytics records are generated using the exposed tool names, providing metrics that align with the client's view of the API.
  • Configuration Management: The PR includes thoughtful warnings for when an override might cause an existing per-tool setting (like a rate limit on a tool that gets renamed) to no longer apply as intended. This helps prevent silent misconfigurations.
  • Upstream Compatibility: The feature is designed to be compatible with any standard Streamable HTTP MCP server. The background catalogue check uses the same transport configuration as the main proxy (including mTLS and authentication), ensuring it can connect to secured upstreams.
Metadata
  • Review Effort: 5 / 5
  • Primary Label: feature

Powered by Visor from Probelabs

Last updated: 2026-11-26T15:28:36.013Z | Triggered by: pr_opened | Commit: 1484500

💡 TIP: You can chat with Visor using /visor ask <your question>

@github-actions

Copy link
Copy Markdown
Contributor

API Changes

--- prev.txt	2026-11-26 15:24:37.985290626 +0000
+++ current.txt	2026-11-26 15:24:32.214314566 +0000
@@ -2312,6 +2312,27 @@
     OAS version. MCP Proxies are OAS-based but with stricter requirements for
     MCP-specific fields.
 
+# Package: ./apidef/mcp/catalogue
+
+package catalogue // import "github.com/TykTechnologies/tyk/apidef/mcp/catalogue"
+
+Package catalogue lists the tools of a remote MCP server, for checking
+x-tyk-mcp-server tool overrides against the upstream catalogue with
+oas.InspectRemoteMCPToolCatalogue or oas.CheckRemoteMCPToolCatalogue.
+
+FUNCTIONS
+
+func FetchToolNames(ctx context.Context, client *http.Client, url string, header http.Header) ([]string, error)
+    FetchToolNames lists every tool name an MCP server exposes over Streamable
+    HTTP: initialize, notifications/initialized, then tools/list following
+    nextCursor until the last page, then a best-effort session DELETE. JSON and
+    text/event-stream responses are accepted.
+
+    header is sent on every request (for example upstream credentials).
+    Redirects are never followed, whatever the client's policy, so header cannot
+    reach another host; a 3xx response is an error. The caller bounds the call
+    through ctx and the client's timeout.
+
 # Package: ./apidef/oas
 
 package oas // import "github.com/TykTechnologies/tyk/apidef/oas"
@@ -2546,6 +2567,16 @@
     AdapterSourceAPIID returns the REST APIID corresponding to a fallback
     synthetic adapter APIID, or "" if id is not an adapter ID.
 
+func CheckRemoteMCPToolCatalogue(ext *TykMCPServer, upstreamToolNames []string) (missingSources []string, err error)
+    CheckRemoteMCPToolCatalogue checks a remote MCP proxy's tool overrides
+    against the complete upstream tool catalogue (every tools/list page).
+
+    It returns an error when an override's final name is also the name of an
+    upstream tool that has no override, because both would then be exposed under
+    the same name. Overrides whose source tool is not in the catalogue expose
+    nothing; their source names are returned as missing and are not an error.
+    See InspectRemoteMCPToolCatalogue for a report of every collision.
+
 func DefaultDerivedParamExplode(style string) bool
     DefaultDerivedParamExplode returns the OpenAPI default explode value for a
     parameter serialization style.
@@ -2693,6 +2724,18 @@
     acknowledging that some standard Tyk OAS API fields are optional in
     templates.
 
+func ValidateRemoteMCPToolOverrides(ext *TykMCPServer) error
+    ValidateRemoteMCPToolOverrides validates x-tyk-mcp-server primitives
+    for a remote MCP proxy, where each primitive selects an upstream tool by
+    source.toolName and may override its name, description and annotations.
+
+    It checks only what the configuration itself can prove: selectors,
+    tool-name syntax, duplicate sources and duplicate final names. Swapping
+    names between overridden tools, or reusing a name freed by another override,
+    is allowed. Collisions with upstream tools that have no override
+    need the upstream catalogue; see InspectRemoteMCPToolCatalogue and
+    CheckRemoteMCPToolCatalogue.
+
 func ValidateSecurityProcessingMode(mode string) bool
     ValidateSecurityProcessingMode validates the security processing mode value.
 
@@ -5744,6 +5787,24 @@
 type ReadableDuration = time.ReadableDuration
     ReadableDuration is an alias maintained to be used in imports.
 
+type RemoteMCPToolCollision struct {
+	// Name is the name both tools would be exposed under.
+	Name string
+	// Source is the upstream tool the override renames to Name.
+	Source string
+}
+    RemoteMCPToolCollision is an override whose final name is also the name of
+    an upstream tool that has no override of its own.
+
+func InspectRemoteMCPToolCatalogue(ext *TykMCPServer, upstreamToolNames []string) (missingSources []string, collisions []RemoteMCPToolCollision)
+    InspectRemoteMCPToolCatalogue compares a remote MCP proxy's tool overrides
+    with the complete upstream tool catalogue (every tools/list page).
+
+    It returns, in configuration order, the sources of overrides that
+    are not in the catalogue, which expose nothing, and the overrides
+    whose final name is also the name of an untouched upstream tool. Use
+    ValidateRemoteMCPToolOverrides for the checks that need no catalogue.
+
 type RequestSizeLimit struct {
 	// Enabled activates the Request Size Limit functionality.
 	//
@@ -6401,6 +6462,9 @@
 	Path string `bson:"path,omitempty" json:"path,omitempty"`
 	// Method selects a source REST operation by HTTP method.
 	Method string `bson:"method,omitempty" json:"method,omitempty"`
+	// ToolName selects an upstream tool by name on a remote MCP proxy. It is
+	// mutually exclusive with the REST selectors above.
+	ToolName string `bson:"toolName,omitempty" json:"toolName,omitempty"`
 }
     TykMCPServerSource identifies the source REST operation behind an MCP
     primitive. OperationID is preferred; path+method is accepted for source
@@ -8304,12 +8368,6 @@
 	// A token with no iss claim is matched by key ID (kid) alone.
 	// It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
 	AllowUnsafeIDPMissingIssuer bool `json:"allow_unsafe_idp_missing_issuer"`
-
-	// AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
-	// It exists for compatibility with browser clients on other origins that connected before the check was added.
-	// Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
-	// To allow a browser client, add its origin to the API's CORS allowed origins instead.
-	AllowUnsafeWebSocketOrigin bool `json:"allow_unsafe_websocket_origin"`
 }
     Config is the configuration object used by Tyk to set up various parameters.
 
@@ -10596,12 +10654,6 @@
 	OAS   oas.OAS
 
 	StripListenPath model.StripListenPathFunc
-
-	// WebSocketOriginAllowed reports whether a WebSocket handshake may
-	// proceed. Bento's http_server output accepts every origin unless its own
-	// cors setting is on, so the Gateway checks the origin first. When nil,
-	// handshakes are refused.
-	WebSocketOriginAllowed func(*http.Request) bool
 }
     APISpec is a subset of gateway.APISpec for the values the middleware
     consumes.
@@ -11603,6 +11655,9 @@
     IsSyntheticMCPAdapter reports whether this spec is a hidden runtime-only
     adapter synthesized for a REST-as-MCP proxy/source pairing.
 
+func (s *APISpec) MCPToolView() *tooloverride.View
+    MCPToolView returns the admitted remote MCP tool view, or nil.
+
 func (a *APISpec) PrepareRequestToLog(r *http.Request) *http.Request
 
 func (a *APISpec) PrepareRequestToLogInPlace(r *http.Request)
@@ -13676,7 +13731,7 @@
 func (m *MCPVEMContinuationMiddleware) Name() string
     Name returns the middleware name for logging and debugging.
 
-func (m *MCPVEMContinuationMiddleware) ProcessRequest(_ http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
+func (m *MCPVEMContinuationMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
     ProcessRequest handles VEM chain continuation logic. This is GENERIC routing
     - just follows the NextVEM chain, no protocol logic.
 

@probelabs

probelabs Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Security Issues (1)

Severity Location Issue
🟡 Warning gateway/mcp_response_decoding.go:127
The 'decodingReadCloser' used for streaming decompression of server-sent event (SSE) responses does not enforce a limit on the total size of the decompressed data. A malicious or compromised upstream server could send a highly compressed stream (a "zip bomb") that, when decompressed, consumes excessive CPU and network bandwidth, leading to a denial of service on the gateway. While non-streaming responses are protected by a size limit, this protection is missing for streaming responses.
💡 SuggestionImplement a limit on the total number of bytes that can be read from a 'decodingReadCloser'. This can be achieved by wrapping the source 'io.ReadCloser' with an 'io.LimitedReader' created with a sensible limit, such as the one provided by 'mcpDecodeLimit(gw.GetConfig().MaxResponseBodySize)'. The reader should return an error if the limit is exceeded.

Architecture Issues (1)

Severity Location Issue
🟡 Warning gateway/mcp_remote_catalogue_upstream.go:29
A temporary `ReverseProxy` instance is created solely to access its `httpTransport` method for building the upstream transport. This pattern, while effective for reusing existing logic, is indirect and creates an unnecessary object.
💡 SuggestionConsider refactoring the transport creation logic out of the `ReverseProxy` type and into a dedicated factory function. This function could be called directly from both the reverse proxy setup and here in `remoteMCPCatalogueClient`, making the code more direct and the dependencies clearer. This would improve the separation of concerns, as transport creation would no longer be tied to the `ReverseProxy` instance.

Performance Issues (1)

Severity Location Issue
🟡 Warning gateway/mcp_remote_tool_view.go:303-313
The `dispatchRemoteMCPToolsCall` function reads the entire request body into memory to perform tool name translation. For large request bodies, this can lead to high memory consumption and garbage collector pressure, potentially impacting gateway performance under heavy load. A similar pattern of in-memory buffering and rewriting is used for `tools/list` responses in `rewriteRemoteMCPToolsList`, which can also be a performance concern for large responses.
💡 SuggestionFor improved performance and lower memory footprint, consider implementing a streaming JSON transformation. This would involve parsing the JSON from the request/response stream, rewriting relevant fields, and streaming the modified JSON without buffering the entire body in memory. Libraries that support streaming JSON processing could be investigated. While more complex, this approach would be more scalable for large payloads.

Powered by Visor from Probelabs

Last updated: 2026-11-26T15:26:33.404Z | Triggered by: pr_opened | Commit: 1484500

💡 TIP: You can chat with Visor using /visor ask <your question>

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
4 New issues
1 Accepted issue

Measures
0 Security Hotspots
91.6% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

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.

1 participant