Skip to content

[TT-18770] MCP Aggregator: per-proxy tool selection - #8905

Merged
andrei-tyk merged 17 commits into
TT-18771-mcp-aggregator-routingfrom
TT-18770-mcp-aggregator-tool-selection
Nov 26, 2026
Merged

andrei-tyk merged 17 commits into
TT-18771-mcp-aggregator-routingfrom
TT-18770-mcp-aggregator-tool-selection

Conversation

@andrei-tyk

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

Copy link
Copy Markdown
Contributor

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

  • Default: leaving out tools includes every tool the proxy exposes. tools: [] is rejected, as it already was.
  • Matching: names match the tool names the proxy exposes after its own renames. The match is exact and case-sensitive.
  • Duplicates: listing the same tool twice is rejected.

Runtime

  • One check, mcpAggregatorSelects, drives both tools/list and tools/call.
  • Unselected tools never appear in the list. Calling one returns HTTP 400 with -32602 unknown tool "<aggregated>", and the proxy is never contacted.
  • Selected tool missing from the proxy's current list: it is left out, with a WARN naming the tool, alias and proxy.
  • Name too long: an aggregated name <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)

  • The TT-18772 probe (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.
  • These are rejected with HTTP 400:
    • A selected tool the proxy doesn't expose, which also covers a tool the proxy's own tool view excludes: tool "delete_repo" not found in aggregated MCP proxy "github".
    • A final name over 128 characters, counted in characters: 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.
  • A proxy that can't be read at admission is admitted with a WARN, and runtime filtering still applies.

Known limits

  • Configs loaded without going through the admission API (for example from file) get runtime filtering only, not the 400s.
  • An API-to-MCP proxy answers a call to a tool excluded by its own view with -32603 internal tool error rather 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

AC Proof
AC-01 default includes all TestMCPAggregatorListsEveryToolWithoutASelection; live
AC-02 subset …ListsOnlySelectedTools, …SelectsByTheNameTheProxyExposes, …FindsSelectedToolsOnLaterPages; live
AC-03 deselected call …RejectsADeselectedToolWithoutCallingTheProxy; live 400, 0 upstream requests
AC-04 per proxy …AppliesEachProxysSelectionIndependently; live
AC-05 unknown selection …RejectsSelectingAToolTheProxyDoesNotExpose, TestHandleAddApiOASRejectsSelectingAToolTheProxyDoesNotExpose; live 400 on POST and PUT
AC-06 later removal …OmitsASelectedToolTheProxyNoLongerExposesWithAWarning; live WARN
AC-07 128 limit …RejectsAggregatedToolNamesOverTheLimit, …OmitsAndRefusesToolsGainedLaterWithNamesOverTheLimit; live 400
AC-08 can't widen …RejectsSelectingAToolExcludedByTheProxysOwnView; live 400
  • The aggregator tests pass with -race. ./internal/mcp/... and ./apidef/... pass, and so does ./gateway with -run 'MCP|Mcp|JSONRPC|Aggregat'.
  • A reviewer's bypass probes all returned 400 with zero upstream requests: case variants, Unicode look-alikes, escapes, a header/body name mismatch, renamed tools, and unchecked configs.

Before / after / demo: see the evidence comment below.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • 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)
  • 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

Ticket Details

TT-18770
Status In Code Review
Summary Select which tools from each aggregated MCP proxy join the aggregate

Generated at: 2026-11-25 23:37:06

andrei-tyk and others added 2 commits November 11, 2026 21:35
…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>
@probelabs

probelabs Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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 tools array in the x-tyk-mcp-aggregator.upstreams[] OAS definition.

If the tools field is omitted, all tools from the upstream are included, ensuring backward compatibility. The feature introduces robust validation at two stages:

  1. Admission Control: When an aggregator API is created or updated, the gateway now actively probes each upstream proxy to fetch its complete list of available tools. The configuration is rejected with a 400 Bad Request if a selected tool does not exist on the upstream, is duplicated in the selection, or if the resulting aggregated tool name (<alias>__<tool>) exceeds MCP's 128-character limit.

  2. Runtime Enforcement: For both tools/list and tools/call requests, the aggregator filters tools based on the selection. Calls to unselected tools are rejected directly by the aggregator with an unknown tool error, without contacting the upstream proxy. The system is also resilient to dynamic changes; if a previously selected tool is no longer exposed by the upstream at runtime, it is gracefully omitted from the list and a throttled warning is logged to prevent log spam.

Files Changed Analysis

The changes are primarily concentrated in the gateway package, with supporting modifications in apidef and internal to support the new feature.

  • apidef/oas/mcp_aggregator.go: The OAS extension schema is updated to include the tools field, with validation to prevent empty arrays, blank names, or duplicate tool selections.
  • gateway/mcp_aggregator_version.go: This file sees the most significant changes, introducing the new admission control logic. The probeUpstream function now fetches the full tool list from each upstream proxy, and validateMCPAggregatorUpstreamViews uses this information to validate the configuration against live data before it's loaded.
  • gateway/mcp_aggregator_runtime.go & gateway/mcp_aggregator_call.go: These files implement the runtime filtering. listUpstreamTools filters the tool list for tools/list and handles warnings for missing tools, while resolveTool uses mcpAggregatorSelects to reject calls to deselected tools. A new warning throttling mechanism (mcpAggregatorWarningThrottle) is also introduced here.
  • internal/mcp/aggregator/index.go: A constant MaxToolNameLength (128) is added to enforce the tool name length limit consistently.
  • New Test Files: Four new test files have been added (..._selection_admission_test.go, ..._selection_probe_test.go, ..._selection_limits_test.go, ..._selection_test.go), providing comprehensive test coverage for the new admission rules, runtime behavior, and various edge cases.

Architecture & Impact Assessment

  • What this PR accomplishes: It provides administrators with granular control over the toolset exposed by an MCP Aggregator, enhancing security by allowing them to create a focused, minimal set of tools and prevent unintended exposure.

  • Key technical changes introduced:

    1. Declarative Tool Selection: A new tools array in the OAS definition allows for explicit inclusion of tools from each upstream.
    2. Stateful Admission Control: The gateway now probes upstreams during the API admission process to fetch their complete tool list. This allows it to validate the configuration against the upstream's actual state, catching integration errors at configuration time rather than at runtime.
    3. Strict Runtime Filtering: The mcpAggregatorSelects function and a new mcpAggregatorToolSelection map are consistently used for both tools/list and tools/call to enforce the selection.
    4. Resilience and Observability: A new warning throttling mechanism (mcpAggregatorWarningThrottle) prevents log spam for recurring issues (like a missing tool) found during runtime checks.
  • Affected system components: The changes are scoped to the MCP Aggregator feature within the Tyk Gateway, primarily affecting the OAS API loading/validation pipeline and the JSON-RPC request handling for tools/list and tools/call.

New Admission Flow

The 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
Loading

Scope Discovery & Context Expansion

The 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

  • gateway/mcp_aggregator_version.go: Contains the core new admission logic in validateMCPAggregatorUpstreamViews and probeUpstream.
  • gateway/mcp_aggregator_call.go: Implements runtime rejection of deselected tools in resolveTool using mcpAggregatorSelects.
  • gateway/mcp_aggregator_runtime.go: Handles filtering of tools for tools/list in listUpstreamTools and introduces mcpAggregatorWarningThrottle.
  • apidef/oas/mcp_aggregator.go: Defines the schema change and validation for the new tools field.
  • gateway/mcp_aggregator_selection_admission_test.go, gateway/mcp_aggregator_selection_probe_test.go, gateway/mcp_aggregator_selection_limits_test.go, gateway/mcp_aggregator_selection_test.go: New test files providing comprehensive coverage for the feature.
Metadata
  • Review Effort: 4 / 5
  • Primary Label: feature

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 /visor ask <your question>

@probelabs

probelabs Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Security Check Passed

No security issues found – changes LGTM.

✅ Security Check Passed

No security issues found – changes LGTM.

\n\n

Architecture Issues (1)

Severity Location Issue
🟡 Warning gateway/mcp_aggregator_call.go:155
The `mcpAggregatorSelects` function, which is in the critical path for every `tools/call` request, uses `slices.Contains` for a linear scan over the selected tools. While this is acceptable for a small number of tools, it has O(N) time complexity and could become a performance bottleneck if an administrator selects a large number of tools for a single upstream. The implementation for `tools/list` already uses a map for O(1) lookups, demonstrating a more performant pattern for the same kind of check.
💡 SuggestionFor consistency and to optimize for cases with many selected tools, consider pre-computing the `Tools` slice into a `map[string]struct{}` when the API definition is loaded or cached. This map could then be used for O(1) lookups in `mcpAggregatorSelects`, similar to how `mcpAggregatorToolSelection` is used for `tools/list`. This would likely involve modifying how the upstream configuration is stored or accessed at runtime to include this pre-computed map.

Performance Issues (1)

Severity Location Issue
🟡 Warning gateway/mcp_aggregator_runtime.go:127
The `mcpAggregatorWarningThrottle.allow` method holds a mutex while performing a cleanup scan of its internal map when it reaches capacity (`mcpAggregatorMaxThrottledWarnings`, set to 10,000). This scan has a time complexity of O(C), where C is the capacity. Since the throttler is global to the gateway, concurrent `tools/list` requests that trigger warnings could contend for this lock. If the map is full of non-expired entries, this potentially slow operation will occur for every new warning, possibly causing latency spikes for `tools/list` calls.
💡 SuggestionTo reduce lock contention, avoid performing the full map scan while the lock is held. One alternative is to use a probabilistic or randomized eviction strategy to make space, which would be an O(1) operation. Another option is to periodically clean expired entries in a separate background goroutine, rather than during a request.

✅ Quality Check Passed

No 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 /visor ask <your question>

@andrei-tyk

andrei-tyk commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Before / after / demo evidence

The demo video mcp-aggregator-selection-demo-silent.mp4 (70 s, silent) is attached to TT-18770.

BEFORE is output recorded on the TT-18771 build (1a16e45ef). On that build:

  • the selection was ignored;
  • a deselected call was forwarded to the upstream;
  • delete_repo, a narrowed view and over-long names were all accepted.

AFTER is a live run against a gateway built from this branch. It shows:

  • the subset list;
  • a deselected call returning 400, with 0 upstream requests;
  • delete_repo rejected;
  • a selection that would widen the proxy's own view rejected;
  • the 128-character limit rejected.

The removal warning (AC-06) is shown in a screenshot and in the Jira AC proof comment, not in the video.

AC before / after

AC What is checked BEFORE (1a16e45ef) AFTER (e74c76a31)
AC-01 No selection means every tool the proxy exposes Already passed. All five tools listed: github__create_issue, github__list_issues, github__search, orders__create_order, orders__list_orders. Pass, unchanged. The same five tools.
AC-02 github selects list_issues: only that github tool is listed Fail. The selection was parsed and ignored; all five tools were still listed. Pass. github__list_issues, orders__create_order, orders__list_orders.
AC-03 Calling a deselected tool (github__create_issue) Fail. HTTP 200: the call was forwarded and the github fixture logged 1 tools/call create_issue. Pass. HTTP 400, -32602 unknown tool "github__create_issue". The fixture logged 0 requests for it; the selected github__list_issues got HTTP 200 and 1 request.
AC-04 Each proxy's selection is independent Fail. All five tools listed whatever each proxy selected. Pass. orders [list_orders, create_order] + github [list_issues] lists 3 tools; changing orders to [list_orders] leaves github__list_issues, orders__list_orders.
AC-05 Selecting a tool the proxy does not expose (delete_repo on github), on create and update Fail. Accepted: POST 200 added, PUT 200 modified. Pass. POST and PUT both HTTP 400 tool "delete_repo" not found in aggregated MCP proxy "github". Nothing saved: after the failed create company-tools is 404; after the failed update it keeps its previous selection.
AC-06 A selected tool disappears from the proxy later (the source drops list_orders) Partly. orders__list_orders dropped out of the list, but no warning was logged. Pass. orders__list_orders is omitted, orders__create_order stays, and the Gateway logs WARN MCP aggregator omits selected tool the aggregated MCP proxy does not expose ... alias=orders tool=list_orders upstream_api_id=orders.
AC-07 Aggregated names over 128 characters (orders__ + a 125-character tool = 133) Fail. Accepted with HTTP 200, with or without a selection, and the 133-character name was listed. Pass. HTTP 400 ... "orders__" plus the tool name is 133 characters, over the 128 character limit for MCP tool names, with and without a selection. Both remedies work: deselecting the tool (lists orders__list_orders) or the alias o (128 characters, listed).
AC-08 A tool the proxy's own view excludes (create_order on orders-narrow) Fail. Accepted: POST 200 added, PUT 200 modified. Pass. POST and PUT both HTTP 400 tool "create_order" not found in aggregated MCP proxy "orders". orders-narrow's own tools/list returns ["list_orders"], which is the view admission checks.

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, tools/list and tools/call follow each proxy's selection. Selections the proxy does not expose and names over 128 characters are rejected with HTTP 400 when the aggregator is saved, and a selected tool that later disappears is omitted with a warning.

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.

@andrei-tyk

Copy link
Copy Markdown
Contributor Author

Demo video and screenshots (TT-18770)

The demo is 70 s and silent.

BEFORE: output recorded on the previous build. There, the selection was ignored and a deselected call was forwarded to the upstream.

AFTER: a live run against a gateway built from this branch. It shows:

  • the subset list;
  • a deselected call returning 400 with 0 upstream requests;
  • delete_repo rejected;
  • a narrowed proxy view rejected;
  • the 128-character limit rejected.
mcp-aggregator-selection-demo-silent.mp4
01-subset-tools-list 02-deselected-call-400-zero-upstream-requests 03-delete-repo-selection-rejected-400 04-omitted-selected-tool-warning-log

@andrei-tyk
andrei-tyk marked this pull request as ready for review November 11, 2026 20:31
andrei-tyk and others added 4 commits November 11, 2026 22:51
…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>
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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>
andrei-tyk and others added 2 commits November 12, 2026 01:32
…ol-selection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@andrei-tyk

Copy link
Copy Markdown
Contributor Author

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 bold-puma-zst4), generated 2026-11-11T23:38:12Z, reviewing commit 1781c96. Three findings, none actioned. Visor edits its own comment in place on every push, so the original text of each finding is quoted below to keep this record readable after that.

# Finding Status Reason
1 security, Error, gateway/mcp_aggregator_call.go:142: an alias containing __ makes the alias/tool split ambiguous ❌ Not actioned Aliases cannot contain _. Details below the table.
2 architecture, Warning, gateway/mcp_aggregator_version.go:287: mcpAggregatorSelectionError does two checks ❌ Not actioned One short function with one caller, answering one question. Details below.
3 performance, Warning, gateway/mcp_aggregator_call.go:159-161: slices.Contains on every tools/call ❌ Not actioned The selection is a few names out of what the proxy exposes. Details below.

1. Alias containing __ makes the split ambiguous. The trigger cannot happen. Every alias must match ^[a-z0-9-]+$ (apidef/oas/mcp_aggregator.go:19, checked at :150), so an alias can never contain _, let alone __. The example alias proxy__internal is refused at admission with "aliases may contain only lowercase letters, digits and hyphens", which TestMCPAggregatorRejectsInvalidAlias pins. Because the alias has no _, the first __ in an aggregated name always ends the alias, and the rest is the tool name even when the tool itself contains __. TestMCPAggregatorSplitsTheAliasAtTheFirstSeparator pins that by routing orders__get__order to tool get__order on orders. The suggested extra check is already covered by the stricter pattern.

What Visor wrote (revision 4, verbatim)

🟠 Error gateway/mcp_aggregator_call.go:142

Issue: The logic for parsing an aggregated tool name into an alias and a tool name is flawed. It uses strings.Cut to split on the first __ separator. However, there is no validation to prevent an upstream alias from also containing __. This ambiguity can lead to incorrect tool resolution. For instance, if an upstream has an alias proxy__internal and a tool my_tool, the aggregated name will be proxy__internal__my_tool. The parser will incorrectly identify the alias as proxy and the tool name as internal__my_tool. This will cause the request to be routed to the wrong upstream proxy (the one with alias proxy) or, more likely, fail authorization checks, resulting in a denial of service for all tools on any upstream whose alias contains the __ separator.

Suggestion: Forbid the use of the __ separator in upstream aliases by adding a validation check. This will remove the parsing ambiguity and ensure correct routing. The validation should be added to the ValidateTykMCPAggregator function in apidef/oas/mcp_aggregator.go. Example of validation to add: go // in apidef/oas/mcp_aggregator.go, inside the validation loop if strings.Contains(upstream.Alias, "__") { return fmt.Errorf("%s.alias %q is invalid: must not contain '__'", field, upstream.Alias) }

2. mcpAggregatorSelectionError does two checks. True that it checks two things: selected tools exist on the proxy, and the aggregated names fit the 128-character limit. Both answer one admission question, "can this proxy's tools be aggregated as configured?", and the function is about 20 lines with a single caller in validateMCPAggregatorUpstreamViews (gateway/mcp_aggregator_version.go:282). Its comment says the length check covers every exposed tool when nothing is selected. Splitting it would add a second function and call site for no change in behaviour.

What Visor wrote (revision 4, verbatim)

🟡 Warning gateway/mcp_aggregator_version.go:287

Issue: The function mcpAggregatorSelectionError combines two distinct validation responsibilities: validating that selected tools are exposed by the upstream proxy, and validating that the final aggregated tool names do not exceed the character limit. This second check is also performed on all exposed tools when no selection is made, which makes the function name potentially misleading as its scope is broader than just the 'selection'.

Suggestion: For improved clarity and separation of concerns, consider splitting this function into two smaller, more focused functions (e.g., validateToolSelection and validateAggregatedToolNames). The primary function could then orchestrate calls to these new functions. While the current implementation is clear due to its comprehensive comment, separating these responsibilities would make the code more modular and easier to maintain, especially if more validation rules are added in the future.

3. slices.Contains on every tools/call. True that it is a linear scan, but over the operator's selection, which admission restricts to tools the proxy actually exposes, and which in practice is a handful of names. Each tools/call also makes an in-process hop through the aggregated proxy's full middleware chain, which costs orders of magnitude more than scanning a short slice. A precomputed set would have to be cached per catalogue generation and kept in step with reloads, which adds state for no measurable gain. We can revisit this if profiling ever shows it.

What Visor wrote (revision 4, verbatim)

🟡 Warning gateway/mcp_aggregator_call.go:159-161

Issue: The mcpAggregatorSelects function uses slices.Contains to check if a tool is selected. This performs a linear scan over the upstream.Tools slice with O(N) time complexity, where N is the number of selected tools. This function is in the critical path for every tools/call request. While efficient for a small number of selected tools, it can become a performance bottleneck if an upstream has a large number of tools selected. The tools/list implementation already converts the tool selection into a map for efficient O(1) lookups; a similar approach should be used for the tools/call path.

Suggestion: To optimize this, the tool selection slice (upstream.Tools) should be converted into a map (map[string]struct{}) once when the API definition is loaded and cached. This pre-computed map can then be used for O(1) lookups in mcpAggregatorSelects, significantly improving performance for tools/call requests with many selected tools.

Quality reported no issues.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

andrei-tyk and others added 4 commits November 17, 2026 13:17
…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>
Comment thread gateway/mcp_aggregator_version.go Resolved
Comment thread gateway/mcp_aggregator_runtime.go Resolved
Comment thread gateway/mcp_aggregator_version.go Resolved
Comment thread gateway/mcp_aggregator_version.go Resolved
Comment thread gateway/mcp_aggregator_runtime.go Resolved
Comment thread gateway/mcp_aggregator_version.go Resolved
Comment thread apidef/oas/mcp_aggregator.go Resolved
edsonmichaque
edsonmichaque previously approved these changes Nov 25, 2026

@edsonmichaque edsonmichaque 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.

LGTM

andrei-tyk and others added 3 commits November 25, 2026 23:42
…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-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.

1 similar comment
@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.

…ol-selection

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.

1 similar comment
@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.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
12 New issues
0 Accepted issues

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

See analysis details on SonarQube Cloud

@edsonmichaque edsonmichaque 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.

LGTM

@andrei-tyk
andrei-tyk removed this pull request from stack #8912 November 26, 2026 10:46
@andrei-tyk
andrei-tyk added this pull request to stack #8988 November 26, 2026 10:47
@andrei-tyk
andrei-tyk merged commit 52c5914 into TT-18767-mcp-aggregator-feature-branch Nov 26, 2026
79 of 130 checks passed
@andrei-tyk
andrei-tyk deleted the TT-18770-mcp-aggregator-tool-selection branch November 26, 2026 11:16
andrei-tyk added a commit that referenced this pull request Nov 26, 2026
…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>
andrei-tyk added a commit that referenced this pull request Nov 26, 2026
## 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>
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.

3 participants