Skip to content

[TT-18772] MCP Aggregator: support only MCP 2026-07-28 - #8903

Merged
andrei-tyk merged 28 commits into
TT-18769-mcp-aggregatorfrom
TT-18772-mcp-aggregator-latest-protocol
Nov 26, 2026
Merged

andrei-tyk merged 28 commits into
TT-18769-mcp-aggregatorfrom
TT-18772-mcp-aggregator-latest-protocol

Conversation

@andrei-tyk

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

Copy link
Copy Markdown
Contributor

Description

Stacked on #8901 (TT-18769). The base is TT-18769-mcp-aggregator, so this diff contains only the protocol work.

The MCP Aggregator now accepts and advertises only MCP 2026-07-28, and calls every aggregated MCP proxy on that version.

  • Admission: an aggregator reports SupportedProtocolVersions() == ["2026-07-28"]. Any other declared version is rejected by the existing ingress check, before authentication, with the gateway's standard 400 -32022 unsupported protocol version {"requested":…, "supported":["2026-07-28"]}. The version can be declared in the header, in _meta, or in initialize.params.protocolVersion. A headerless request falls back to 2025-03-26, which is not offered, so it is rejected the same way. Other proxy types keep their version matrix and fallback. The ingress output for non-aggregator endpoints is byte-identical to the base across the 3,822-case review matrix.
  • server/discover and initialize: both declare the tools capability only and the 2026-07-28 version only. serverInfo is under _meta["io.modelcontextprotocol/serverInfo"].
    • Clients that start with initialize are supported through an opt-in for aggregators only. It accepts an initialize where the header and params agree, with no _meta, and a notifications/initialized (202, or -32600 if it carries an id).
    • The aggregator keeps no session.
  • Compatibility probe when an upstream is added: on create or update, every aggregated proxy is probed in-process on 2026-07-28 (server/discover, with tools/list as fallback). The probes run concurrently, within a budget equal to proxy_default_timeout (10 s if unset), and from loopback.
    • An upstream that is incompatible is rejected with aggregated MCP proxy "<id>" does not support MCP version 2026-07-28: <detail>. Incompatible means one of: it returns -32022, it rejects the version, it declares another version, or it requires a legacy session.
    • An upstream that is down is admitted with a warning.
    • The probe's trust only covers server/discover and tools/list, for the same upstream and org.
  • Version lost at runtime: an aggregated proxy that stops serving 2026-07-28 is left out of tools/list, with a warning naming it and the version mismatch. The other proxies keep serving.

Known limits:

  • A header-unaware 2025-03-26 server without server/discover cannot be told apart from a modern server that skips discovery, so it is admitted with a warning.
  • Aggregator create and update can block for up to the proxy timeout while the probes run.

Related Issue

TT-18772 (epic TT-18767)

Motivation and Context

One predictable protocol contract for the aggregate, with no translation between versions across aggregated proxies.

How This Has Been Tested

AC Proof
AC-01 2026-07-28 served TestMCPAggregatorServesRequestsDeclaringTheLatestVersion; live 200
AC-02 2025-11-25 rejected, lists 2026-07-28 TestMCPAggregatorRejectsOlderDeclaredVersions; live 400 -32022 (header, _meta, initialize, no credential)
AC-03 legacy headerless rejected TestMCPAggregatorRejectsLegacyHeaderlessRequests; live 400 -32022
AC-04 discover advertises only 2026-07-28 TestMCPAggregatorDiscoveryAdvertisesOnlyTheLatestVersion, …InitializeNegotiatesOnlyTheLatestVersion, …ServesInitializeFirstClients…; live
AC-05 aggregated proxies called on 2026-07-28 TestMCPAggregatorCallsAggregatedProxiesOnTheLatestVersion; live upstream header log
AC-06 legacy-only proxy rejected when added TestMCPAggregatorRejectsAggregatedProxyWithoutTheLatestVersion, …RejectsSessionFirstLegacyAggregatedProxy; live 400 for version-first and session-first upstreams
AC-07 later downgrade omitted with warning TestMCPAggregatorOmitsAggregatedProxyThatLostTheLatestVersion, …RedeployedOnASessionFirstLegacyServer; live warning
AC-08 direct proxy calls unchanged TestMCPAggregatorVersionRestrictionLeavesOtherMCPProxiesAlone; live 200 on 2025-11-25 and headerless

The aggregator tests pass with -race, as do ./internal/mcp/... and ./apidef/.... go test ./gateway/ -run 'MCP|Mcp' passes too. The existing failures TestCheckActivePollerLoop and TestLooping/VirtualEndpoint_or_plugins also fail on the base.

Live checks ran on a kyt oss stack with the mock MCP server and small Python MCP servers that each speak one protocol version (legacy version-first, legacy session-first, and dual).

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, including the probe timeout vs write_timeout note)
  • 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-18772
Status In Code Review
Summary Support only the latest MCP protocol version on the aggregator

Generated at: 2026-11-25 23:27:58

andrei-tyk and others added 9 commits November 11, 2026 16:23
Adds the x-tyk-mcp-aggregator OAS extension and its MCP JSON schema (at most 50 aggregated proxies), plus an IsMCPAggregator classifier that needs an MCP API with the reserved tyk://mcp-aggregator upstream and, on the gateway's APISpec, the extension. A non-MCP API or an MCP proxy without the extension that loops to an API named mcp-aggregator keeps proxying as before.
ACs: AC-01

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Rejects aggregators with no or more than 50 aggregated MCP proxies, the same proxy listed twice, invalid or duplicate aliases, empty tool selections, and aggregated proxies that are unknown, not loaded on this gateway, not MCP proxies, aggregators, or owned by another organisation (403). One classifier with reason codes backs these checks, and they run in the MCP management API and the generic OAS API paths next to the existing API-to-MCP source checks.
ACs: AC-03, AC-04, AC-05, AC-06, AC-07, AC-08, AC-10, AC-11

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Builds an immutable aggregator snapshot in loadApps next to the API-to-MCP pairing index, mapping each aggregator to its admitted aggregated MCP proxies and each proxy to the aggregators that reference it. Proxies the shared admission classifier rejects (not loaded, another organisation, aggregator, not MCP) are left out with a warning naming them, so the remaining ones keep serving.
ACs: AC-09, AC-12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The MCP management API and the generic API delete now answer 409 naming the aggregators that still reference the proxy, using the aggregator index. Deleting a referenced proxy would otherwise silently remove tools from a live aggregator endpoint.
ACs: AC-12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The aggregator's listen path now answers MCP JSON-RPC after its own middleware chain: tools/list fans out in-process to every aggregated MCP proxy over the 2026-07-28 protocol, prefixes tool names as alias__tool, and omits proxies that are not loaded, fail, repeat a cursor, need more than 100 pages or exceed the response size limit, with a warning naming them. Calls carry a one-hop loop trust whose session only grants the admitted proxy and is dropped before that proxy loops to another API, and the catalogue is read live so source changes show up after a reload.
ACs: AC-01, AC-02, AC-09, AC-13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An MCP aggregator now reports 2026-07-28 as its only supported version, so ingress validation rejects older declarations and headerless legacy requests with the unsupported protocol version error before authentication runs. Legacy initialize negotiation is kept only for endpoints that serve a legacy version, leaving other MCP proxies unchanged.
ACs: AC-01, AC-02, AC-03, AC-08

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The aggregator now answers server/discover with 2026-07-28 as its only supported version, the tools capability and its serverInfo in _meta, and answers both discover-first and initialize-first clients on that version. An initialize declaring 2026-07-28 in the header and params, with or without _meta, gets tools-only capabilities and notifications/initialized is accepted as a no-op, while other MCP proxies keep the existing ingress rules.
ACs: AC-04

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Creating or updating an aggregator now probes each aggregated MCP proxy in-process with server/discover, falling back to tools/list, on 2026-07-28 from a loopback caller within the gateway's proxy timeout, and rejects the definition when a proxy rejects that version or asks for a legacy session. A proxy that cannot be checked, or whose support is not confirmed because it has no server/discover, is admitted with a warning and left to the runtime failure isolation.
ACs: AC-06

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tools/list fan-out now reports an aggregated proxy that answers 2026-07-28 with an unsupported version signal as a version mismatch, omitting it with a warning that names the proxy and the version while the other proxies keep serving. Tests assert that the fan-out reaches aggregated proxies with the 2026-07-28 header, mirrored method and _meta through a helper reusable for tools/call.
ACs: AC-05, AC-07

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

probelabs Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

This PR updates the MCP Aggregator to exclusively support the 2026-07-28 protocol version. This change enforces a single, modern communication standard for the aggregator, its clients, and all aggregated upstream MCP proxies, eliminating the need for version negotiation or translation.

Key changes include:

  • Strict Protocol Enforcement: The aggregator now advertises and accepts only the 2026-07-28 protocol version. It rejects any incoming request that declares a different version (including legacy headerless requests) with a 400 Bad Request error before authentication.
  • Upstream Compatibility Probing: A new validation step is introduced for creating or updating an aggregator. The gateway now actively probes each configured upstream MCP proxy to ensure it supports 2026-07-28. Configurations with incompatible upstreams are rejected, while unavailable upstreams are admitted with a warning.
  • Runtime Safety: If a previously compatible upstream proxy stops supporting the required protocol at runtime, it is gracefully omitted from the aggregated tools/list result, and a warning is logged. This prevents a single misbehaving upstream from affecting the entire aggregator.
  • initialize Handshake Support: The aggregator now supports clients that use the initialize handshake, but only when they are communicating on the 2026-07-28 protocol. This is managed through a new ServesModernInitialize interface, ensuring other MCP proxy types remain unaffected.

Files Changed Analysis

This is a significant feature addition, introducing over 1,800 lines of code across 17 files, with minimal deletions. The changes are concentrated in the gateway/ and internal/mcp/ directories.

  • New Files: Five new files have been added. gateway/mcp_aggregator_version.go contains the core logic for the new upstream probing mechanism. The other four (gateway/mcp_aggregator_compat_test.go, gateway/mcp_aggregator_downgrade_test.go, gateway/mcp_aggregator_probe_order_test.go, gateway/mcp_aggregator_protocol_test.go) provide extensive test coverage for the new protocol enforcement, compatibility checks, and runtime behaviors.
  • Modified Files: Existing aggregator files (gateway/mcp_aggregator_*.go) are updated to integrate the strict versioning and probing logic. internal/mcp/ingress_validation.go is modified to handle the aggregator's unique protocol rules, and gateway/mw_mcp_aggregator_loop_auth.go is updated to securely accommodate the new probing functionality by restricting probe calls to read-only methods.

Architecture & Impact Assessment

  • What this PR accomplishes: It standardizes the MCP Aggregator on a single protocol version (2026-07-28), simplifying its architecture and ensuring a predictable contract for all interacting services.

  • Key technical changes introduced:

    1. Strict Ingress Control: The aggregator's SupportedProtocolVersions() now returns only ["2026-07-28"], and ingress validation rejects all other versions.
    2. Upstream Version Probing: At configuration time, probeMCPAggregatorUpstreams is called to probe each upstream MCP proxy and verify its compatibility. This is a blocking operation bounded by proxy_default_timeout.
    3. Runtime Enforcement: The mcpAggregatorDispatcher now wraps upstream calls to detect and handle mcpAggregatorVersionMismatchError, ensuring incompatible upstreams are safely excluded from results.
    4. Secure Probing Mechanism: The mcpAggregatorLoopTrust struct is extended with a Probe flag, which the MCPAggregatorLoopAuthBypassMiddleware uses to restrict probes to read-only discovery methods (server/discover, tools/list).
  • Affected system components:

    • MCP Aggregator
    • API Definition Admission Control (for APIs and MCPs)
    • MCP Ingress Validation Logic
    • Internal Loopback Authentication Middleware

Upstream Probing on Aggregator Create/Update

sequenceDiagram
    participant Admin as "Admin API Call"
    participant Gateway as "Gateway API Handler"
    participant ProbingLogic as "probeMCPAggregatorUpstreams()"
    participant UpstreamProxy as "Upstream MCP Proxy"

    Admin->>Gateway: POST /tyk/apis (Create/Update Aggregator)
    activate Gateway
    Gateway->>ProbingLogic: Start Probing
    activate ProbingLogic
    ProbingLogic->>UpstreamProxy: server/discover (v=2026-07-28)
    note right of ProbingLogic: In-process call with<br/>'Probe' trust
    alt Upstream is Compatible
        UpstreamProxy-->>ProbingLogic: OK, supportedVersions: ["2026-07-28"]
        ProbingLogic-->>Gateway: Probe Succeeded
    else Upstream is Incompatible
        UpstreamProxy-->>ProbingLogic: Error: unsupported version
        ProbingLogic-->>Gateway: Probe Failed (Version Mismatch)
    end
    deactivate ProbingLogic

    alt All Probes Succeeded
        Gateway->>Gateway: Save API Definition
        Gateway-->>Admin: 200 OK
    else Any Probe Failed
        Gateway-->>Admin: 400 Bad Request
    end
    deactivate Gateway
Loading

Scope Discovery & Context Expansion

The changes are well-contained within the gateway's MCP functionality, specifically targeting the Aggregator type while ensuring other MCP proxies are unaffected, as confirmed by tests like TestMCPAggregatorVersionRestrictionLeavesOtherMCPProxiesAlone. The introduction of a Probe flag in the mcpAggregatorLoopTrust struct is a key architectural detail, enabling secure, limited-trust, in-process calls to inspect upstream capabilities during configuration. The ServesModernInitialize interface provides a clean pattern for extending functionality for a specific component without impacting existing ones.

Metadata
  • Review Effort: 4 / 5
  • Primary Label: feature

Powered by Visor from Probelabs

Last updated: 2026-11-25T23:31:15.229Z | Triggered by: pr_updated | Commit: f1d60d2

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

@probelabs

probelabs Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Architecture Check Passed

No architecture issues found – changes LGTM.

\n\n

✅ Architecture Check Passed

No architecture issues found – changes LGTM.

\n\n

Performance Issues (1)

Severity Location Issue
🟡 Warning gateway/mcp_aggregator_version.go:189
The `probeVersion` function, which validates an upstream MCP proxy, can block for up to twice the configured timeout. It sequentially attempts two operations (`server/discover` and a fallback `tools/list`), and each is given the full timeout budget (`mcpAggregatorProbeTimeout`). If the first operation times out, the second one is still attempted with another full timeout. This can cause the management API call for creating/updating an aggregator to block for an unexpectedly long time (e.g., 20 seconds with the default 10-second timeout), negatively impacting the user experience of the management API.
💡 SuggestionTo ensure a predictable upper bound on blocking time, use a single timeout context that is shared across both the `server/discover` and `tools/list` probe steps within a single `probeVersion` call. This would cap the total time for validating one upstream to `mcpAggregatorProbeTimeout`. This involves creating the timeout context in `probeVersion` and passing it down to `probeStep`, rather than having `probeStep` create its own timeout.

Quality Issues (2)

Severity Location Issue
🟡 Warning gateway/mcp_aggregator_version.go:50-122
The function `mcpAggregatorVersionMismatch` is long and handles multiple concerns, including parsing different response formats (JSON, plain text, event-stream) and checking for various structural and text-based signals for version incompatibility. Its high cyclomatic complexity and multiple nested conditional blocks make it difficult to understand and maintain.
💡 SuggestionRefactor this function by breaking it down into smaller, single-responsibility functions. For example, create separate helpers for: 1. Checking for structural mismatches (e.g., from headers or `_meta` field). 2. Handling and interpreting JSON-RPC error responses. 3. Parsing plain-text error messages for incompatibility signals. This will improve readability, reduce complexity, and make the logic easier to test and modify in the future.
🟡 Warning gateway/mcp_aggregator_version.go:89-110
The logic for detecting version mismatches relies on string matching for specific error messages from upstream services (e.g., `asksForLegacySession`, `mentionsUnsupportedProtocolVersion`). While this is pragmatic, it's inherently brittle and may break if upstream MCP SDKs or services change their error message wording.
💡 SuggestionWhile the extensive test coverage in `TestMCPAggregatorVersionMismatchSignals` mitigates this risk significantly, consider adding comments directly above the string-matching logic in `asksForLegacySession` and `mentionsUnsupportedProtocolVersion` that reference the specific test(s) validating them. This creates a clear link between the implementation and its contract test, making it easier for future developers to update both if an upstream SDK's error messages change.

Powered by Visor from Probelabs

Last updated: 2026-11-25T23:30:58.015Z | Triggered by: pr_updated | Commit: f1d60d2

💡 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 is mcp-aggregator-protocol-demo-silent.mp4, attached to TT-18772. It runs 73 s and has no sound.

  • BEFORE: output recorded on the TT-18769 build (1db2af01d). There, 2025-11-25 and headerless requests were served, discover and initialize returned -32601, and a legacy-only upstream was admitted.

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

    • 2026-07-28 tools/list returning 200;
    • 2025-11-25 and headerless requests rejected with -32022, supported ["2026-07-28"];
    • server/discover advertising only 2026-07-28;
    • a legacy-only upstream rejected when added to the aggregator;
    • a direct call to github on 2025-11-25 still served.
  • Not in the video:

    • AC-05: upstream request headers.
    • The session-first part of AC-06.
    • AC-07: the runtime downgrade warning.

    These are covered by the Go tests, the screenshots and the live re-run outputs in the Jira AC proof comment.

AC before / after

BEFORE = 1db2af01d (the aggregator story this change is stacked on), recorded from proofs/BEFORE/out.txt against a gateway built from that commit (https://localhost:8281). Same client requests as the AFTER proofs.
AFTER = branch HEAD 472dc7b52, live kyt env mcpagg at https://localhost:8381, from rerun/AC-NN.txt. The video and screenshots were captured on 2026-11-11 against the same stack.

Fixtures: mock MCP :7978 (serves 2026-07-28 and the legacy versions), :7979 legacy-only server that checks the version first (2025-03-26 only), :7980 dual recording server (2026-07-28 and 2025-11-25), :7981 legacy-only server that checks the session first.

AC Scenario BEFORE (1db2af01d, recorded) AFTER (472dc7b52, live)
AC-01 tools/list on /company-tools/ declaring 2026-07-28 (header and _meta) 200 with 17 tools 200 with 17 tools: orders__* (2) and github__* (15)
AC-02 tools/list declaring 2025-11-25: header and _meta; _meta only; legacy initialize session; no credential header and _meta: 200 with 17 tools. initialize offering 2025-11-25: 404 -32601 method not supported by MCP aggregator, no session All four: 400 -32022 unsupported protocol version, data: {"requested":"2025-11-25","supported":["2026-07-28"]}. Without a credential the response is the same 400, so the version check runs before authentication and no tools leak
AC-03 Headerless legacy client: tools/list, headerless initialize offering 2025-03-26, legacy Mcp-Session-Id tools/list: 200 with 17 tools. initialize: 404 -32601, no session All three: 400 -32022, requested: "2025-03-26", supported: ["2026-07-28"]
AC-04 server/discover and initialize declaring 2026-07-28 server/discover: 404 -32601 method not supported by MCP aggregator. initialize: 404 -32601 method removed in the modern protocol server/discover: 200, supportedVersions ["2026-07-28"], capabilities {"tools":{}}, serverInfo company-tools in _meta. initialize: 200, protocolVersion 2026-07-28, capabilities tools only. Initialize-first client without _meta: 200. notifications/initialized: 202. The same initialize sent directly to /github/ keeps the existing proxy rule (400 -32602 missing _meta)
AC-05 Aggregating a dual upstream (github-dual on :7980, serves 2026-07-28 and 2025-11-25) Not recorded. The previous build had no admission check (see AC-06) Admission sends one server/discover with Mcp-Protocol-Version: 2026-07-28 and _meta 2026-07-28; update 200. Aggregated tools/list 200 (github__list_issues, github__search_repos, orders__*); the upstream log shows tools/list forwarded on 2026-07-28. A 2025-11-25 client calling /github-dual/ directly still negotiates 2025-11-25
AC-06 Adding a legacy-only upstream to an aggregator (create and update), for both kinds of legacy server Version-first legacy-github (:7979): new aggregator legacy-tools accepted, 200 added. Session-first server not recorded Version-first: 400 aggregated MCP proxy "legacy-github" does not support MCP version 2026-07-28: upstream rejected it: ... (supported versions: 2025-03-26). Session-first (:7981): 400 ... "legacy-github-sf" does not support MCP version 2026-07-28: upstream requires a legacy session: Bad Request: Mcp-Session-Id header is required. Nothing saved: company-tools unchanged, legacy-tools 404. An unreachable upstream (:7999) is still admitted with a WARN ... admits aggregated MCP proxy without a protocol version check
AC-07 An aggregated proxy loses 2026-07-28 after admission (github's upstream switched to :7979, then :7981) Closest record: tools/list on legacy-tools returns 200 with "tools":[]; WARN MCP aggregator omits aggregated MCP proxy ... reason="tools/list failed: tools/list failed with HTTP 400", which does not name the version tools/list 200 with only orders__*; WARN MCP aggregator omits aggregated MCP proxy ... alias=github mcp_protocol_version=2026-07-28 reason="version mismatch: does not support MCP version 2026-07-28: upstream rejected it: ..." and, for the session-first server, ... upstream requires a legacy session: .... github is restored to :7978 afterwards
AC-08 Direct MCP proxies keep legacy versions /github/ with a 2025-11-25 session: initialize 200 negotiated 2025-11-25, then tools/list 200 Unchanged: /github/ on 2025-11-25 and headerless 2025-03-26, and /orders/ (API-to-MCP) on both. Each initialize returns 200 with the requested version, then tools/list returns 200. Meanwhile /company-tools/ returns 400 -32022 for 2025-11-25

Go tests at 472dc7b52: rerun/go-tests.txt (internal/mcp, adapter, aggregator, pairing and the gateway packages pass).

Screenshots are attached to TT-18772: the -32022 rejection, the discover result, the session-first legacy upstream rejection, and the downgrade warning log. The installed GitHub CLI 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-18772)

The demo is 73 s and silent. The BEFORE section is recorded output from the previous build. The AFTER section is a live run against a gateway built from this branch. It shows:

  • a tools/list declaring 2026-07-28;
  • 2025-11-25 and headerless requests rejected with -32022;
  • server/discover advertising only 2026-07-28;
  • a legacy-only upstream rejected when it is added;
  • a direct 2025-11-25 call to github that still works.
mcp-aggregator-protocol-demo-silent.mp4
01-tools-list-2025-11-25-rejected-400-32022 02-server-discover-latest-only 03-session-first-legacy-upstream-rejected-400 04-omitted-proxy-warning-log

@andrei-tyk
andrei-tyk marked this pull request as ready for review November 11, 2026 20:31
andrei-tyk and others added 7 commits November 11, 2026 22:42
The aggregator now carries the client IP it resolved from X-Real-IP, X-Forwarded-For or the connection into each aggregated MCP proxy's chain, so request.RealIP returns the same address on both hops. IP allow and block lists on an aggregated proxy now see the agent's address instead of the load balancer's, without copying any consumer headers.

ACs: CI/review follow-up

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The merged tools/list now holds at most 10000 tools and 32 MiB of tool definitions, and an aggregated MCP proxy that would push it over either bound is omitted with a warning while the rest keep being served. Reading a proxy's tools/list pages also stops once the proxy alone lists more than the catalogue can hold, so one proxy cannot buffer more than that.

ACs: CI/review follow-up

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tocol

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The aggregated MCP proxies now see the agent's client IP on runtime calls, so the loopback probe test also sends X-Real-IP and X-Forwarded-For on the admin request. The probe must still reach an allow-listed proxy from loopback, whatever address the admin caller claims.

ACs: CI/review follow-up

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The parallel subtests of TestValidateMCPObject copied one OAS document and called SetTykExtension on the copy, which writes to the extensions map they all share, so -race failed about one run in five. This race already exists on master; each subtest now builds its own document, and production code is unchanged.

ACs: CI/review follow-up

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each tools/list now gives every configured aggregated MCP proxy an equal share of the 32 MiB catalogue byte budget, and caps each response at what is left of that share, so all the responses buffered for one tools/list together stay within the budget however the reads interleave. A proxy that goes past its share is omitted with a warning, whatever the other proxies return, while the tool count limit stays a single deterministic bound on the merged list.

ACs: CI/review follow-up

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tocol

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:33:14.837669898 +0000
+++ current.txt	2026-11-25 23:33:08.284818523 +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,11 @@
 
 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 (a *APISpec) SetCompiledErrorOverrides(compiled *CompiledErrorOverrides)
     SetCompiledErrorOverrides stores the compiled error overrides.
 
@@ -11619,7 +11681,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 +13610,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
 }

andrei-tyk and others added 2 commits November 11, 2026 23:54
The aggregator's response recorder now appends an aggregated proxy's response straight to its in-memory buffer, so the bytes are no longer handed to an http.ResponseWriter Write sink. The JSON-RPC request body map is created without a computed capacity hint, which removes the allocation-size overflow warning.

CI/review follow-up

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tocol

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
andrei-tyk and others added 3 commits November 12, 2026 01:25
Log a failed JSON-RPC response write in the aggregator instead of
dropping the error, check the loop-auth context flag's type assertion,
and rename the loop-auth context key so it no longer reads as a
hard-coded credential. Check every error the aggregator tests ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tocol

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Check every error the protocol and compatibility tests and their test
upstreams ignored, and mark the aggregator's in-process upstream request
as a gosec G704 false positive: it is served by the aggregated proxy's
own chain and never sent over the network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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 5 commits November 17, 2026 13:17
…tocol

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tocol

# Conflicts:
#	gateway/mcp_aggregator_dispatch.go
#	gateway/mw_mcp_aggregator_loop_auth.go
…tocol

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.

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

Comment thread gateway/mcp_aggregator_admission.go Outdated
}
}
return "", 0
return gw.validateMCPAggregatorUpstreamVersions(r, &APISpec{APIDefinition: &incoming}, ext, upstreams)

@edsonmichaque edsonmichaque Nov 25, 2026 •

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.

The probes run before the ID checks. Is it expected that a create probes without an aggregator ID, and that an update with the wrong ID probes every upstream before it's rejected?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No, that was a bug. Fixed in 1917b71: the validateMCP middleware now only runs the checks that make no upstream calls, and the Gateway API handlers run the version probe after their API ID checks. A create probes under its final (generated if absent) API ID, and an update whose body ID doesn't match the path is rejected before any upstream is called. Tests: TestMCPAggregatorUpdateWithAMismatchedAPIIDProbesNoUpstream, TestMCPAggregatorCreateProbesUnderItsFinalAPIID.

Comment thread gateway/mcp_aggregator_version.go Outdated
if isMCPAggregatorVersionMismatch(err) {
return err
}
if _, listErr := d.send(parent, spec, mcp.MethodToolsList, map[string]any{}, trust); listErr != nil {

@edsonmichaque edsonmichaque Nov 25, 2026 •

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.

Discover and this tools/list call share one timeout. What happens to this call when discover is slow?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It could run out of time: a discover that used most of the budget left tools/list almost none, so a mismatch on tools/list could be reported as "could not check". Fixed in 1917b71: server/discover and the tools/list fallback each get the full probe timeout. Test: TestMCPAggregatorProbeGivesToolsListItsOwnTimeout (discover hangs, tools/list returns a legacy-session error, create is rejected).

Comment thread gateway/mcp_aggregator_version.go Outdated
if r != nil {
ctx = r.Context()
}
ctx, cancel := context.WithTimeout(ctx, gw.mcpAggregatorProbeTimeout())

@edsonmichaque edsonmichaque Nov 25, 2026 •

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.

Every update probes all upstreams again. Should a rename fail if an upstream has since dropped 2026-07-28?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No, it shouldn't. Fixed in 1917b71: an update only probes aggregated proxies that the loaded aggregator doesn't already admit (from #8905 on, also when alias or tool selection changed). Already-admitted proxies are handled by the runtime on every tools/list, which leaves out one that stopped serving 2026-07-28, so a rename no longer fails. Tests: TestMCPAggregatorUpdateDoesNotReprobeAdmittedUpstreams, TestMCPAggregatorUpdateProbesOnlyNewUpstreams.

The Gateway API handlers now run the aggregator's upstream version probe
once the request has passed its API ID checks, so a create probes under
its final API ID and a request those checks reject never reaches an
upstream. The validateMCP middleware keeps only the checks that make no
upstream calls.

server/discover and the tools/list fallback each get the whole probe
timeout, so a slow discover no longer leaves tools/list without time.

An update probes only the aggregated proxies the loaded aggregator does
not already admit; the runtime keeps serving or omitting the others, so
a rename no longer fails because such a proxy changed since admission.

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.

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.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
10 New issues
0 Accepted issues

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

See analysis details on SonarQube Cloud

@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 f9507ad into TT-18767-mcp-aggregator-feature-branch Nov 26, 2026
97 of 101 checks passed
@andrei-tyk
andrei-tyk deleted the TT-18772-mcp-aggregator-latest-protocol branch November 26, 2026 11:16
andrei-tyk added a commit that referenced this pull request Nov 26, 2026
…ng, cancellation and timeout (#8904)

## Description

**Stacked on #8903 (TT-18772), which is stacked on #8901 (TT-18769).**
The base is `TT-18772-mcp-aggregator-latest-protocol`, so this diff
shows only the routing work.

The MCP Aggregator now serves the full tool session itself and routes
each `tools/call` to the aggregated MCP proxy that owns the tool.

**Building the tool list**
- **Descriptors:** each upstream tool descriptor is kept raw. Only its
top-level `name` is prefixed with `<alias>__`.
- **Order and filtering:** the list is sorted by aggregated name, then
filtered with the consumer's MCP rules (session `mcp_access_rights` and
OAS `mcpTools`, matched on aggregated names), so filtering never
reorders the result.
- **Caching:** the list always carries `cacheScope: "private"` and
`ttlMs: 0`, and cache hints from upstreams are dropped. The gateway
response cache is never used for aggregator responses.
- **`ping`:** answered by the aggregator through a narrow opt-in that
only aggregators use. Other proxies still treat `ping` as removed on
2026-07-28. The ingress matrix for non-aggregator endpoints is
byte-identical to the base (3,822 cases).

**Routing `tools/call`**
- **Resolution:** the name is split at the first `__` and resolved from
config only. The alias must exist and pass admission and index checks,
with a hook left for TT-18770's tool selection. The call is forwarded
exactly once to the owning proxy through its own chain, under single-hop
loop trust. No `tools/list` is sent first, so each call counts once
against the proxy's limits.
- **Pass-through:** only the `name` is spliced, so `arguments`, `_meta`
and unknown fields pass through byte-for-byte. The splicer fails closed
on a duplicate or case-variant `name`. `Mcp-Name` is set to the original
tool name, and client `Mcp-Param-*` headers are forwarded.
- **Results:** the proxy's `result`, including `isError`, `content`,
`structuredContent` and extra fields, is returned unchanged. A proxy's
JSON-RPC error is returned byte-for-byte with HTTP 200, so a proxy 401
or 429 can never look like the aggregator's own auth failure or
throttling.
- **Errors raised by the aggregator itself:**

| Case | HTTP | JSON-RPC |
|---|---|---|
| Unknown alias | 400 | -32602 `unknown tool "<name>"` |
| Proxy reports an unknown tool (go-sdk or adapter wording) | 400 |
-32602 `unknown tool "<name>"` |
| Proxy unavailable (not loaded, down, 5xx, invalid reply) | 503 |
-33006 `upstream unavailable` |
| Timeout | 504 | -33006 `upstream timeout` |

**Cancellation and timeout**
- Each upstream call runs on a child of the agent request's context. An
agent that closes its exchange cancels only that call; no result is
written.
- `notifications/cancelled` is acknowledged with 202. Under 2026-07-28
each POST is its own exchange, which matches go-sdk stateless servers.
- The aggregator's `upstream.enforceTimeout` bounds every upstream call.
The bound holds even when a proxy ignores cancellation, because the
chain runs in a goroutine with a select and panic recovery.

**Pre-existing gateway issues found during review.** Both reproduce on
`origin/master`; neither is introduced or worsened here, and they will
be raised separately:
- The API-level `GlobalRateLimit` on an MCP proxy is counted on every
VEM hop (`mw_jsonrpc.go:179`, `mw_api_rate_limit.go:75`). A 10/min limit
refuses the 4th direct call.
- Name-based MCP blocklists match case-sensitively
(`internal/mcp/list_filter.go:642`). A case-variant name can reach a
case-insensitive upstream. Allow-lists fail closed.

## Related Issue

[TT-18771](https://tyktech.atlassian.net/browse/TT-18771) (epic
[TT-18767](https://tyktech.atlassian.net/browse/TT-18767))

## Motivation and Context

Agents connect to one aggregator endpoint, discover the combined tools
and call any of them through a single standards-compliant MCP session.

## How This Has Been Tested

All 21 ACs have Go tests (run with `-race`) and a live proof on a kyt
`oss` stack built from this branch. The stack uses local fixtures for
recording, slow, rotating-order, cache-hint and down upstreams, plus an
API-to-MCP proxy over local httpbin. Full per-AC proofs are in the Jira
AC comment.

| Area | ACs | Key tests |
|---|---|---|
| Tool list and caching | 01-10, 20 | `…InitializeDeclaresOnlyTools`,
`…AnswersPing`, `…ListsToolsWithTheirDescriptorsUnchanged`,
`…OrdersToolsByAggregatedName`,
`…FiltersToolsPerConsumerKeepingTheOrder`,
`…ListIsPrivateAndImmediatelyStale`,
`…ListIsNotSharedBetweenConsumersWithResponseCaching`,
`…OmitsAggregatedProxyWhoseUpstreamIsDown` |
| Invocation | 04, 11-16, 21 | `…SplitsTheAliasAtTheFirstSeparator`,
`…RoutesToolCallToTheOwningProxy`,
`…SendsEachToolCallToTheProxyExactlyOnce`, `…RejectsUnknownTools`,
`…PassesArgumentsAndMetadataThroughExactly`,
`…PassesToolResultsThroughUnchanged`,
`…AnswersProxyJSONRPCErrorsWithHTTP200`,
`…ReportsAnUnavailableProxyOnlyForItsOwnTools` |
| Lifetime | 17-19 | `…CancelsTheUpstreamCallWhenTheAgentCancels`,
`…CancellingOneCallLeavesTheOthersRunning`, `…TimesOutASlowToolCall`,
`…TimeoutBoundsAProxyThatIgnoresCancellation` |

- The suites `./internal/mcp/...`, `./apidef/...`, and `./gateway` with
`-run 'MCP|Mcp'` show no new failures against the base.
`TestLooping/VirtualEndpoint_or_plugins` and `TestCheckActivePollerLoop`
fail on the base as well.
- Coordinator re-run: 117 aggregator and MCP tests pass under `-race`.

**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 (docs follow once
the epic's Gateway stories land)
- [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-18771]:
https://tyktech.atlassian.net/browse/TT-18771?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ








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

### Ticket Details

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

|         |    |
|---------|----|
| Status  | In Code Review |
| Summary | Route tool calls from the aggregator to aggregated MCP
proxies |

Generated at: 2026-11-25 23:27:56

</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 #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](https://tyktech.atlassian.net/browse/TT-18770) (epic
[TT-18767](https://tyktech.atlassian.net/browse/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)
- [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)
- [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-18770]:
https://tyktech.atlassian.net/browse/TT-18770?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ









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

### Ticket Details

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

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

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

</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
…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