Repository navigation
[TT-18770] MCP Aggregator: per-proxy tool selection - #8905
andrei-tyk merged 17 commits into
Conversation
…ist and tools/call An aggregated MCP proxy with a tools selection contributes only those tools, matched exactly on the name the proxy exposes, and a call to a deselected tool, or to one whose aggregated name exceeds MCP's 128-character limit, is rejected as unknown without reaching the proxy. A selected tool the proxy no longer exposes, and a tool whose aggregated name is over the limit, are left out of tools/list with a warning naming the tool, alias and proxy. ACs: AC-01, AC-02, AC-03, AC-04, AC-06 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ool view at admission The admission probe now reads every tools/list page of each aggregated MCP proxy along with its version check, and rejects a tool selected twice, a selected tool the proxy's own view does not expose, or an aggregated tool name over MCP's 128-character limit. A proxy that cannot be read is still admitted with a warning, and the runtime applies its selection once it answers. ACs: AC-05, AC-07, AC-08 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
This PR introduces a significant enhancement to the MCP Aggregator, allowing administrators to select which tools from an upstream MCP proxy are exposed in the final aggregate. This is configured via a new optional If the
Files Changed AnalysisThe changes are primarily concentrated in the
Architecture & Impact Assessment
New Admission FlowThe diagram below illustrates the enhanced admission control process, which now includes probing the upstream for its tool list to perform validation before saving the API definition. sequenceDiagram
participant Client
participant Gateway as Tyk Gateway
participant Upstream as Upstream MCP Proxy
Client->>Gateway: POST /tyk/apis/oas (Create/Update Aggregator)
activate Gateway
Gateway->>Gateway: validateMCPAggregatorUpstreamViews()
Note over Gateway: For each new or changed upstream proxy...
Gateway->>Upstream: probeUpstream():<br/>1. server/discover (version check)<br/>2. tools/list (fetch all pages)
activate Upstream
Upstream-->>Gateway: Discovery info & Tool list
deactivate Upstream
Gateway->>Gateway: mcpAggregatorSelectionError():<br/>- Validate selection against exposed tools<br/>- Check aggregated name length
alt Validation Fails
Gateway-->>Client: 400 Bad Request
else Validation Succeeds
Gateway->>Gateway: Load API Definition
Gateway-->>Client: 200 OK
end
deactivate Gateway
Scope Discovery & Context ExpansionThe most significant architectural shift is making the API admission process more active and intelligent. Previously, it performed a simple, stateless version check. Now, it fetches state (the tool list) from upstream dependencies to validate its own configuration. This "shift-left" approach to validation makes the system more robust by catching configuration and integration errors early. The runtime checks serve as a secondary defense, handling dynamic changes in an upstream's toolset after the aggregator has been loaded. For example, if a selected tool is later removed from a proxy, the aggregator logs a throttled warning and continues to function with the remaining available tools, demonstrating a resilient design. The changes are well-contained within the MCP aggregator's logic and do not appear to impact other gateway features. References
Metadata
Powered by Visor from Probelabs Last updated: 2026-11-25T23:32:14.209Z | Triggered by: pr_updated | Commit: d720ed7 💡 TIP: You can chat with Visor using |
✅ Security Check PassedNo security issues found – changes LGTM. ✅ Security Check PassedNo security issues found – changes LGTM. \n\nArchitecture Issues (1)
Performance Issues (1)
✅ Quality Check PassedNo quality issues found – changes LGTM. Powered by Visor from Probelabs Last updated: 2026-11-25T23:31:34.619Z | Triggered by: pr_updated | Commit: d720ed7 💡 TIP: You can chat with Visor using |
Before / after / demo evidenceThe demo video BEFORE is output recorded on the TT-18771 build (
AFTER is a live run against a gateway built from this branch. It shows:
The removal warning (AC-06) is shown in a screenshot and in the Jira AC proof comment, not in the video. AC before / after
Summary: AC-01 already held, because no selection already meant all tools. Before this change, selections were parsed and ignored: deselected tools were listed and forwarded, and invalid or over-long selections were saved. On the branch head, Screenshots are attached to TT-18770. GitHub CLI here cannot attach media, so the video and screenshots will be added to this PR by drag-and-drop. |
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Admission now checks a tool selection against a set of the exposed names, and tools/list checks each exposed tool against a set of the selected names, instead of scanning a slice per tool. A single tools/call lookup keeps the slice scan, and a test checks that both paths select the same tools. ACs: CI/review follow-up Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bound on the aggregated catalogue applies after tool selection, so a proxy that exposes many tools but has few selected still fits. The new test covers a proxy listing 9999 tools with one selected next to another proxy. ACs: CI/review follow-up Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
API Changes --- prev.txt 2026-11-25 23:49:06.063903236 +0000
+++ current.txt 2026-11-25 23:48:57.429923475 +0000
@@ -98,6 +98,11 @@
// Application protocols
AppProtocolMCP = "mcp"
+
+ // MCPAggregatorTargetURL is the reserved upstream URL of an MCP aggregator.
+ // An aggregator serves its catalogue from aggregated MCP proxies on the same
+ // gateway and never proxies to this URL.
+ MCPAggregatorTargetURL = "tyk://mcp-aggregator"
)
const (
GraphQLEngineDataSourceKindREST = "REST"
@@ -402,6 +407,12 @@
func (a *APIDefinition) IsMCP() bool
IsMCP returns true if this API uses the Model Context Protocol.
+func (a *APIDefinition) IsMCPAggregator() bool
+ IsMCPAggregator returns true if this MCP API uses the reserved MCP
+ aggregator upstream. A non-MCP API with that target is an ordinary loop to
+ an API named "mcp-aggregator". The gateway's APISpec additionally requires
+ the x-tyk-mcp-aggregator extension.
+
func (a *APIDefinition) IsMCPManaged() bool
IsMCPManaged reports whether this API belongs to the MCP management surface.
@@ -2293,8 +2304,9 @@
CONSTANTS
const (
- ExtensionTykAPIGateway = "x-tyk-api-gateway"
- ExtensionTykMCPServer = "x-tyk-mcp-server"
+ ExtensionTykAPIGateway = "x-tyk-api-gateway"
+ ExtensionTykMCPServer = "x-tyk-mcp-server"
+ ExtensionTykMCPAggregator = "x-tyk-mcp-aggregator"
)
FUNCTIONS
@@ -2375,6 +2387,9 @@
// ExtensionTykMCPServer is the OAS schema key for REST-as-MCP proxy tool-view configuration.
ExtensionTykMCPServer = "x-tyk-mcp-server"
+ // ExtensionTykMCPAggregator is the OAS schema key for MCP aggregator configuration.
+ ExtensionTykMCPAggregator = "x-tyk-mcp-aggregator"
+
// Main holds the default version value (empty).
Main = ""
@@ -2491,6 +2506,13 @@
DefaultPRMWellKnownPath is the default well-known path for OAuth 2.0
Protected Resource Metadata (RFC 9728).
+const MCPAggregatorTargetURL = apidef.MCPAggregatorTargetURL
+ MCPAggregatorTargetURL is the reserved upstream URL of an MCP aggregator.
+
+const MaxMCPAggregatorUpstreams = 50
+ MaxMCPAggregatorUpstreams is the most aggregated MCP proxies one aggregator
+ may list. The JSON schema enforces the same limit.
+
VARIABLES
@@ -2696,6 +2718,10 @@
func ValidateSecurityProcessingMode(mode string) bool
ValidateSecurityProcessingMode validates the security processing mode value.
+func ValidateTykMCPAggregator(ext *TykMCPAggregator) error
+ ValidateTykMCPAggregator validates the aggregator settings that do not
+ depend on other APIs loaded on the gateway.
+
TYPES
@@ -4777,6 +4803,10 @@
func (s *OAS) GetTykExtension() *XTykAPIGateway
GetTykExtension returns our OAS schema extension from inside *OAS.
+func (s *OAS) GetTykMCPAggregatorExtension() *TykMCPAggregator
+ GetTykMCPAggregatorExtension returns the parsed MCP aggregator extension,
+ if present.
+
func (s *OAS) GetTykMCPServerExtension() *TykMCPServer
GetTykMCPServerExtension returns the parsed REST-as-MCP proxy tool-view
extension, if present.
@@ -4850,6 +4880,9 @@
func (s *OAS) RemoveTykExtension()
RemoveTykExtension clears the Tyk extensions from *OAS.
+func (s *OAS) RemoveTykMCPAggregatorExtension()
+ RemoveTykMCPAggregatorExtension clears the MCP aggregator extension.
+
func (s *OAS) RemoveTykMCPServerExtension()
RemoveTykMCPServerExtension clears the REST-as-MCP proxy tool-view
extension.
@@ -4863,6 +4896,9 @@
func (s *OAS) SetTykExtension(xTykAPIGateway *XTykAPIGateway)
SetTykExtension populates our OAS schema extension inside *OAS.
+func (s *OAS) SetTykMCPAggregatorExtension(ext *TykMCPAggregator)
+ SetTykMCPAggregatorExtension populates the MCP aggregator extension.
+
func (s *OAS) SetTykMCPServerExtension(ext *TykMCPServer)
SetTykMCPServerExtension populates the proxy-side REST-as-MCP extension.
@@ -6339,6 +6375,23 @@
GetTykExtensionConfigParams extracts a *TykExtensionConfigParams from a
*http.Request.
+type TykMCPAggregator struct {
+ // Upstreams lists the aggregated MCP proxies.
+ Upstreams []TykMCPAggregatorUpstream `bson:"upstreams,omitempty" json:"upstreams,omitempty"`
+}
+ TykMCPAggregator configures an MCP proxy that serves the combined tool
+ catalogue of other MCP proxies loaded on the same gateway.
+
+type TykMCPAggregatorUpstream struct {
+ // APIID is the ID of the aggregated MCP proxy.
+ APIID string `bson:"apiId" json:"apiId"`
+ // Alias prefixes the aggregated proxy's tool names as `<alias>__<tool>`.
+ Alias string `bson:"alias" json:"alias"`
+ // Tools selects tools of the aggregated proxy. Omitted means all tools.
+ Tools []string `bson:"tools,omitempty" json:"tools,omitempty"`
+}
+ TykMCPAggregatorUpstream references one aggregated MCP proxy.
+
type TykMCPServer struct {
// Primitives configures proxy-side source selection and metadata overrides.
Primitives []TykMCPServerPrimitive `bson:"primitives,omitempty" json:"primitives,omitempty"`
@@ -11580,6 +11633,10 @@
func (a *APISpec) Init(authStore, healthStore, orgStore storage.Handler)
+func (a *APISpec) IsMCPAggregator() bool
+ IsMCPAggregator reports whether this spec is an MCP aggregator: an MCP API
+ with the reserved aggregator upstream and an x-tyk-mcp-aggregator extension.
+
func (a *APISpec) IsPRMEnabled() bool
IsPRMEnabled reports whether this API serves Protected Resource Metadata via
either location: the new oauth2 security scheme block (GetOAuth2PRMConfig,
@@ -11603,6 +11660,15 @@
func (a *APISpec) SanitizeProxyPaths(r *http.Request)
+func (s *APISpec) ServesModernInitialize() bool
+ ServesModernInitialize reports whether this endpoint answers a modern
+ initialize itself: the MCP aggregator negotiates 2026-07-28 for clients that
+ still open with initialize.
+
+func (s *APISpec) ServesModernPing() bool
+ ServesModernPing reports whether this endpoint answers ping on 2026-07-28
+ itself: the MCP aggregator answers it locally.
+
func (a *APISpec) SetCompiledErrorOverrides(compiled *CompiledErrorOverrides)
SetCompiledErrorOverrides stores the compiled error overrides.
@@ -11619,7 +11685,8 @@
func (s *APISpec) SupportedProtocolVersions() []string
SupportedProtocolVersions describes the runtime behind this endpoint. Native
and paired REST-as-MCP endpoints serve the same four Gateway-qualified
- versions once the cached stateless adapter handler is active.
+ versions once the cached stateless adapter handler is active. An MCP
+ aggregator serves only the modern version and has no legacy fallback.
func (a *APISpec) URLAllowedAndIgnored(r *http.Request, rxPaths []URLSpec, whiteListStatus bool) (RequestStatus, interface{})
URLAllowedAndIgnored checks if a url is allowed and ignored.
@@ -13547,6 +13614,42 @@
MCPAdapterRuntime groups runtime-only state for a synthetic REST-as-MCP
adapter API.
+type MCPAggregatorLoopAuthBypassMiddleware struct {
+ *BaseMiddleware
+}
+ MCPAggregatorLoopAuthBypassMiddleware admits trusted in-process calls from
+ an MCP aggregator into one of its aggregated MCP proxies.
+
+func (m *MCPAggregatorLoopAuthBypassMiddleware) EnabledForSpec() bool
+
+func (m *MCPAggregatorLoopAuthBypassMiddleware) Name() string
+
+func (m *MCPAggregatorLoopAuthBypassMiddleware) ProcessRequest(_ http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
+
+type MCPAggregatorLoopAuthRestoreMiddleware struct {
+ *BaseMiddleware
+}
+ MCPAggregatorLoopAuthRestoreMiddleware ends the authentication skip started
+ by MCPAggregatorLoopAuthBypassMiddleware.
+
+func (m *MCPAggregatorLoopAuthRestoreMiddleware) EnabledForSpec() bool
+
+func (m *MCPAggregatorLoopAuthRestoreMiddleware) Name() string
+
+func (m *MCPAggregatorLoopAuthRestoreMiddleware) ProcessRequest(_ http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
+
+type MCPAggregatorMiddleware struct {
+ *BaseMiddleware
+}
+ MCPAggregatorMiddleware serves an MCP aggregator's JSON-RPC methods after
+ the aggregator's own middleware chain, including authentication, has run.
+
+func (m *MCPAggregatorMiddleware) EnabledForSpec() bool
+
+func (m *MCPAggregatorMiddleware) Name() string
+
+func (m *MCPAggregatorMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int)
+
type MCPListFilterResponseHandler struct {
BaseTykResponseHandler
} |
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note Opus 5.5 is answering on behalf of the user. The findings were read and checked against the code; this comment records why they are not being actioned. The user has reviewed and approved it before posting. Visor revision 4 (runId
1. Alias containing What Visor wrote (revision 4, verbatim)
2. What Visor wrote (revision 4, verbatim)
3. What Visor wrote (revision 4, verbatim)
Quality reported no issues. |
|
|
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…egator-tool-selection # Conflicts: # gateway/mcp_aggregator_version.go
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Once server/discover confirms 2026-07-28, a failing tools/list only means the tools could not be checked, even when its error reads like a version mismatch. - The per-proxy tool limit counts selected tools only, and definitions of unselected tools are not kept, so a proxy with more tools than an aggregator may serve can be narrowed to the few it selects. - Without a selection, a tool whose aggregated name exceeds 128 characters is left out with a warning at admission, as at runtime; selecting such a tool by name is still rejected. - The missing-selected-tool and name-too-long warnings, which every uncached tools/list repeats, are logged at most once per 10 minutes for the same aggregator, proxy and tool. - Empty or blank tool names in a selection are rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
SentinelOne CNS Hardcoded Secret Detector 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. |
1 similar comment
|
SentinelOne CNS Hardcoded Secret Detector 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. |
…ol-selection Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
SentinelOne CNS Hardcoded Secret Detector 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. |
1 similar comment
|
SentinelOne CNS Hardcoded Secret Detector 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. |
|
52c5914
into
TT-18767-mcp-aggregator-feature-branch
…middleware (#8906) ## Description This PR is stacked on #8905 (TT-18770), which in turn sits on #8904, #8903 and #8901. Its base is `TT-18770-mcp-aggregator-tool-selection`. It secures the MCP Aggregator with the gateway's standard authentication, policies, rate limits and middleware. It also fixes an existing gateway bug in how MCP rate limits are counted. **Gateway fix: MCP API-level rate limit counted once per request** - On an MCP proxy, `RateLimitForAPI` counted the API-wide `GlobalRateLimit` on every internal VEM routing hop. One `tools/call` cost three units, so a 10/min limit refused the 4th call. This reproduces on `origin/master`. - The API-wide bucket is now skipped only on the API's own VEM hops (`isOwnMCPJSONRPCVirtualEndpointHop`). The JSON-RPC routing state now records the API that owns it, so the following are counted once, and correctly: - a request that one MCP API loops into a second MCP API (`tyk://B`) still spends B's limits; - a versioned child served through its base takes over the base's routing state (`handOverMCPRoutingState`). - The key-level guard (`RateLimitAndQuotaCheck`) uses the same scoped check. On `origin/master`, B's per-key limit was skipped for chained calls too. - Endpoint-specific (per-tool) limits are unchanged. **Aggregator security** - **Authentication:** it runs once, at the aggregator. A missing key gets 401. A key that is valid only for an aggregated proxy gets 403. - **Tool policies:** the existing `mcp_access_rights` / `mcp_primitives` / OAS `mcpTools` rules match aggregated names (`orders__.*`), both for `tools/list` filtering and for blocking `tools/call`. - **Per-tool rate limits** on aggregated names are enforced. The aggregator's limits and the aggregated proxy's own API-level limits stack. The aggregated proxy's consumer-level quotas are not applied, because the consumer session is never forwarded. - **Request-header transforms:** - Headers that the aggregator's request-header transform sets are forwarded to the tool call. Only the names the transform recorded are forwarded, with their post-transform values. - Credentials and protocol headers are never forwarded: Authorization, Cookie, `Proxy-*`, `Mcp-*`, `X-Tyk-*`, `X-Forwarded-*`, X-Real-IP, Forwarded, Host and hop-by-hop headers. - The client IP travels separately: see #8901. - **Generic refusals from API-to-MCP proxies:** these become a proper JSON-RPC error object. The code comes from the chain's error classification, kept even when OTel or OpenTracing wraps the chain, so a rate limit maps to -33004, quota to -33003, IP blocked to -33005, and so on. **Known behaviours (to document)** - Policy tool rules are anchored regular expressions, so write `orders__.*`, not `orders__*`. - A rate-limit refusal from an aggregated proxy reaches the agent as HTTP 200 with a JSON-RPC error. An aggregator-level limit answers HTTP 429. ## Release note **Upgrade impact:** on MCP proxies, the API-level rate limit now counts each request once. Before this fix, each internal JSON-RPC routing hop was also counted, so one `tools/call` used several units of the limit. After upgrading, an MCP proxy with an API-level rate limit accepts the number of requests it is configured for, which is more than it effectively accepted before. Review API-level rate limits on MCP proxies that were tuned to the old behaviour. Per-key limits of an MCP proxy reached through another MCP proxy (`tyk://`) are now applied, as configured. ## Related Issue [TT-18773](https://tyktech.atlassian.net/browse/TT-18773) (epic [TT-18767](https://tyktech.atlassian.net/browse/TT-18767)) ## Motivation and Context Admins control who can use the aggregated endpoint and which tools each consumer can call, with the same controls as other MCP proxies. ## How This Has Been Tested | AC | Proof | |---|---| | AC-01 valid key | `TestMCPAggregatorAuthenticatesOnceAtTheAggregator`; live 200 | | AC-02 missing key | same; live 401, no tool names leaked | | AC-03 proxy-only key | same; live 403 | | AC-04 policy allows `orders__.*`, blocks `github__.*` | `TestMCPAggregatorPolicyToolPatternsMatchAggregatedNames`; live only orders tools | | AC-05 blocked call | same; live 403 -33002, 0 requests reach github | | AC-06 namespaced block | `TestMCPAggregatorPolicyBlocksANamespacedTool`; live | | AC-07 per-tool 5/min | `TestMCPAggregatorPolicyRateLimitsAToolByItsAggregatedName`; live 6th → 429 | | AC-08 limits stack | `TestMCPAggregatorRateLimitsStackAcrossChains`; live 11th refused by the orders chain (-33004) | | AC-09 proxy consumer quota not applied | `TestMCPAggregatorIgnoresConsumerQuotasOfTheAggregatedProxy`; live 7/7 | | AC-10 transform applies | `TestMCPAggregatorRequestHeaderTransform…`, `…ForwardsTransformHeadersAlongsideTheClientIP`; live upstream gets `X-Acme-Tenant`, no Authorization or Cookie | | Rate-limit fix | `TestMCPProxyAPIRateLimitCountsEachRequestOnce`, `TestAPIToMCPProxyAPIRateLimitCountsEachRequestOnce`, `TestChainedMCPProxyStillSpends*`, `TestVersionedMCPProxyCountsEachRequestOnce`, `TestAPIRateLimitStillCountsLoopsOutsideMCPRouting`; live 11th / chained 4th / versioned 4th refused | | Tracing | `TestMCPAggregatorKeepsTheProxyChainsErrorClassificationWithTracing` (OTel off and on) | - **Test runs:** - `go test ./gateway/ -run 'MCPAggregator|Aggregat|MCP|Mcp|RateLimit|Quota|Version' -race -p 1` passes. - `./internal/mcp/...` and `./apidef/...` pass with `-race`. - The new exact-count tests pin the Redis rolling limiter. - **Pre-existing failures, not caused by this PR:** - Known timing flakes that also fail on base: `TestAPIRateLimitResponseHeaders`, `TestProcessRequestOffThreadQuotaLimit` and `TestRequestThrottling`. - A race in `TestMCPVersioning_ConcurrentVersionCreation` that reproduces on base. **Before / after / demo:** see the evidence comment below. ## Types of changes - [x] 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 follow once the epic's Gateway stories land: regex tool rules, HTTP 200 for chained rate-limit errors) - [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-18773]: https://tyktech.atlassian.net/browse/TT-18773?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ <!---TykTechnologies/jira-linter starts here--> ### Ticket Details <details> <summary> <a href="https://tyktech.atlassian.net/browse/TT-18773" title="TT-18773" target="_blank">TT-18773</a> </summary> | | | |---------|----| | Status | In Code Review | | Summary | Secure an MCP Aggregator with authentication, policies and middleware | Generated at: 2026-11-25 23:27:53 </details> <!---TykTechnologies/jira-linter ends here--> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Description This PR is stacked on #8906 (TT-18773), which sits on #8905, #8904, #8903 and #8901. Its base is `TT-18773-mcp-aggregator-security`. It depends on TykTechnologies/tyk-pump#1141, which adds `MCPStats.AggregatorAPIID`; `go.mod` pins that pump commit. It records analytics for MCP Aggregator traffic so routed calls can be told apart from direct ones. - **The aggregator's own record.** Before this change the aggregator wrote no analytics record at all, because it answers inside its own middleware. It now writes one record per request through the existing `mcpCompletionAnalyticsOwner`. The record has the JSON-RPC method and the namespaced tool name (`tools/call`, `orders__list_orders`), and the JSON-RPC error code taken from the response. - **Origin on the routed proxy's record.** When the aggregator calls an aggregated MCP proxy in-process, that proxy's record gets `mcp_stats.aggregator_api_id` set to the aggregator's API ID, plus the tag `mcp-aggregator-<id>`. That tag can be filtered in today's Dashboard without a schema change. - Only the dispatcher sets the value (`exchange()`, `gateway/mcp_aggregator_dispatch.go`). It uses a private context key built from the same in-process loop trust the chain is given. Nothing reads it from headers, and the upstream context drops every caller value except the client IP. - It counts only for the API the trust names. Further hops get no origin, such as the `tyk://` loop on to the REST API behind an API-to-MCP proxy. - Because it is set at dispatch, refusals early in the proxy's chain (IP blocklist, rate limit) also carry the origin. - Internal `tools/list` fan-out records carry it too, with method `tools/list`, so discovery is never counted as a tool call. - **API-to-MCP proxies now report MCP analytics.** This is in its own commit, e491272. `recordMCPDetails` now runs for `IsMCPManaged()` instead of `IsMCP()`. A proxy saved through `/tyk/mcps` is MCP-managed but `IsMCP()` is false, so its records had `is_mcp:false` and no tool name. The REST API behind the proxy keeps `is_mcp:false`, and the synthetic adapter stays `DoNotTrack`, so nothing is double-counted. - **Tracing** needed no change: the in-process hop already carries the span context. A test now pins it. Note that org-wide MCP totals count a routed call twice, once on the aggregator and once on the proxy. That is by design and matches the ticket. Per-API numbers are exact. ## Related Issue [TT-18774](https://tyktech.atlassian.net/browse/TT-18774) (epic [TT-18767](https://tyktech.atlassian.net/browse/TT-18767)) ## Motivation and Context Operators need to see agent usage through the aggregator without it inflating or hiding direct consumer traffic on the aggregated MCP proxies. They also need one connected trace to find which hop failed. ## How This Has Been Tested | AC | Proof | |---|---| | AC-01 aggregator record | `TestMCPAggregatorRecordsTheNamespacedToolCallWithoutAnOrigin`; live company-tools record `tools/call` / `orders__list_orders`, no origin | | AC-02 routed record tagged | `TestMCPAggregatorMarksTheRoutedProxyRecordWithItsOrigin` and `…ErrorRecordWithItsOrigin` (traces on and off), `TestMCPAggregatorMarksToolsListFanOutRecordsWithItsOrigin`; live orders record `aggregator_api_id: company-tools`, tag `mcp-aggregator-company-tools` | | AC-03 direct traffic untagged | `TestMCPProxyDirectCallHasNoAggregatorOrigin` (with and without five look-alike headers); live, same | | AC-04 trace spans both hops | `TestMCPAggregatorTraceHasTheRoutedProxySpanAsAChildOfTheAggregatorSpan`; live, one trace whose root is the company-tools span, with the github entry span as its child (7 spans via OTLP) | - `go test ./gateway/ -run 'MCPAggregator|Aggregat|MCP' -race -count=1` passes. `./internal/mcp/...` and `./apidef/...` pass too. - golangci-lint `--new-from-rev` reports 0 issues. - Live proofs ran on a kyt stack built from this branch with analytics enabled. Records were read from Redis and decoded with tyk-pump's own serializer; traces came from an OTLP receiver. - **Pre-existing failure, not caused by this PR:** `TestAnalytics_Write/.../Detailed_analytics_with_latency`, which also fails on the TT-18773 base and is marked flaky. **Before / after / demo:** see the evidence comment below. ## 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 (analytics docs follow with the epic: `aggregator_api_id`, the `mcp-aggregator-<id>` tag, and API-to-MCP proxies now reporting MCP stats) - [x] I explained why this PR updates go.mod in detail with reasoning why it's required (tyk-pump is bumped to the commit that adds `MCPStats.AggregatorAPIID`, TykTechnologies/tyk-pump#1141) - [ ] I would like a code coverage CI quality gate exception and have explained why 🤖 Generated with [Claude Code](https://claude.com/claude-code) [TT-18774]: https://tyktech.atlassian.net/browse/TT-18774?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ <!---TykTechnologies/jira-linter starts here--> ### Ticket Details <details> <summary> <a href="https://tyktech.atlassian.net/browse/TT-18774" title="TT-18774" target="_blank">TT-18774</a> </summary> | | | |---------|----| | Status | In Code Review | | Summary | Capture analytics for MCP Aggregator traffic | Generated at: 2026-11-25 23:28:04 </details> <!---TykTechnologies/jira-linter ends here--> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>







Description
This PR is stacked on #8904 (TT-18771), then #8903 and #8901. Its base is
TT-18771-mcp-aggregator-routing, so the diff shows only tool selection.Administrators can now choose which tools each aggregated MCP proxy contributes to the aggregate, using
x-tyk-mcp-aggregator.upstreams[].tools.How selection works
toolsincludes every tool the proxy exposes.tools: []is rejected, as it already was.Runtime
mcpAggregatorSelects, drives bothtools/listandtools/call.-32602 unknown tool "<aggregated>", and the proxy is never contacted.<alias>__<tool>over 128 characters is left out of the list with a WARN and refused on call. This covers proxies that gain a long tool after admission.Admission (create and update)
probeUpstream) now reads each proxy's complete current tool view in-process, following every page. It runs once per proxy and still checks the version.tool "delete_repo" not found in aggregated MCP proxy "github".tool "<name>" of aggregated MCP proxy "orders" cannot be aggregated: "orders__" plus the tool name is 133 characters, over the 128 character limit for MCP tool names.Known limits
-32603 internal tool errorrather than unknown tool. That is existing proxy behaviour, and it only shows up when no selection filters the call.Related Issue
TT-18770 (epic TT-18767)
Motivation and Context
Agents get a focused tool list, and tools that must not be exposed through a shared endpoint can't be reached by guessing their name.
How This Has Been Tested
TestMCPAggregatorListsEveryToolWithoutASelection; live…ListsOnlySelectedTools,…SelectsByTheNameTheProxyExposes,…FindsSelectedToolsOnLaterPages; live…RejectsADeselectedToolWithoutCallingTheProxy; live 400, 0 upstream requests…AppliesEachProxysSelectionIndependently; live…RejectsSelectingAToolTheProxyDoesNotExpose,TestHandleAddApiOASRejectsSelectingAToolTheProxyDoesNotExpose; live 400 on POST and PUT…OmitsASelectedToolTheProxyNoLongerExposesWithAWarning; live WARN…RejectsAggregatedToolNamesOverTheLimit,…OmitsAndRefusesToolsGainedLaterWithNamesOverTheLimit; live 400…RejectsSelectingAToolExcludedByTheProxysOwnView; live 400-race../internal/mcp/...and./apidef/...pass, and so does./gatewaywith-run 'MCP|Mcp|JSONRPC|Aggregat'.Before / after / demo: see the evidence comment below.
Types of changes
Checklist
🤖 Generated with Claude Code
Ticket Details
TT-18770
Generated at: 2026-11-25 23:37:06