Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
0bef831
TT-18770: Apply each aggregated MCP proxy's tool selection to tools/l…
andrei-tyk Nov 11, 2026
e74c76a
TT-18770: Check tool selections against each aggregated MCP proxy's t…
andrei-tyk Nov 11, 2026
93edb0a
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 11, 2026
2daf540
TT-18770: Look up selected tools in a set
andrei-tyk Nov 11, 2026
84dceee
TT-18770: Check that the catalogue bound counts only selected tools
andrei-tyk Nov 11, 2026
58fc480
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 11, 2026
01ff67c
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 11, 2026
c873a0a
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 11, 2026
1781c96
TT-18770: Check the write error in the MCP aggregator selection test
andrei-tyk Nov 11, 2026
ae0b0ce
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 17, 2026
8993f41
Merge branch 'TT-18771-mcp-aggregator-routing' into TT-18770-mcp-aggr…
andrei-tyk Nov 19, 2026
552826b
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 24, 2026
b2d96a3
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 24, 2026
19a94bd
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 25, 2026
97b95f7
TT-18770: Address tool selection review findings
andrei-tyk Nov 25, 2026
a476157
TT-18770: Rewrap the aggregator probe doc comment
andrei-tyk Nov 25, 2026
d720ed7
Merge TT-18771-mcp-aggregator-routing into TT-18770-mcp-aggregator-to…
andrei-tyk Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apidef/oas/mcp_aggregator.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@

// ValidateTykMCPAggregator validates the aggregator settings that do not
// depend on other APIs loaded on the gateway.
func ValidateTykMCPAggregator(ext *TykMCPAggregator) error {

Check failure on line 125 in apidef/oas/mcp_aggregator.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 25 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AaHpW9fGLlYXYJrpFm1L&open=AaHpW9fGLlYXYJrpFm1L&pullRequest=8905
if ext == nil {
return nil
}
Expand Down Expand Up @@ -157,6 +157,16 @@
if upstream.Tools != nil && len(upstream.Tools) == 0 {
return fmt.Errorf("%s.tools: select at least one tool or omit the field", field)
}
tools := make(map[string]struct{}, len(upstream.Tools))
for toolIdx, tool := range upstream.Tools {
Comment thread
edsonmichaque marked this conversation as resolved.
Resolved
if strings.TrimSpace(tool) == "" {
return fmt.Errorf("%s.tools[%d]: a tool name cannot be empty or blank", field, toolIdx)
}
if _, duplicate := tools[tool]; duplicate {
return fmt.Errorf("%s.tools[%d] %q is duplicated: each tool may be selected only once", field, toolIdx, tool)
}
tools[tool] = struct{}{}
}
}

return nil
Expand Down
30 changes: 30 additions & 0 deletions apidef/oas/mcp_aggregator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,36 @@ func TestValidateTykMCPAggregator(t *testing.T) {
}},
wantErr: "x-tyk-mcp-aggregator.upstreams[0].tools: select at least one tool or omit the field",
},
{
name: "tool selected twice",
ext: TykMCPAggregator{Upstreams: []TykMCPAggregatorUpstream{
upstream("orders-mcp", "orders", "list_orders"),
upstream("github-mcp", "github", "list_issues", "search", "list_issues"),
}},
wantErr: `x-tyk-mcp-aggregator.upstreams[1].tools[2] "list_issues" is duplicated: each tool may be selected only once`,
},
{
name: "empty tool name",
ext: TykMCPAggregator{Upstreams: []TykMCPAggregatorUpstream{
upstream("github-mcp", "github", "list_issues", ""),
}},
wantErr: "x-tyk-mcp-aggregator.upstreams[0].tools[1]: a tool name cannot be empty or blank",
},
{
name: "blank tool name",
ext: TykMCPAggregator{Upstreams: []TykMCPAggregatorUpstream{
upstream("orders-mcp", "orders", "list_orders"),
upstream("github-mcp", "github", " \t"),
}},
wantErr: "x-tyk-mcp-aggregator.upstreams[1].tools[0]: a tool name cannot be empty or blank",
},
{
name: "same tool name selected on different aggregated proxies",
ext: TykMCPAggregator{Upstreams: []TykMCPAggregatorUpstream{
upstream("orders-mcp", "orders", "search"),
upstream("github-mcp", "github", "search"),
}},
},
}

for _, tt := range tests {
Expand Down
24 changes: 14 additions & 10 deletions gateway/mcp_aggregator_admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gateway
import (
"fmt"
"net/http"
"slices"
"strings"

"github.com/TykTechnologies/tyk/apidef"
Expand Down Expand Up @@ -48,14 +49,16 @@ func (gw *Gateway) validateMCPAggregatorUpstreams(_ *http.Request, mcpObj *oas.O

// probeMCPAggregatorUpstreams checks that the aggregated MCP proxies of an
// incoming aggregator serve MCP 2026-07-28, the only version an aggregator
// uses to call them. The Gateway API handlers call it after the request's API
// ID checks, so a create probes under the aggregator's final API ID and a
// request those checks reject never reaches an upstream.
// uses to call them, and expose every tool the aggregator selects from them.
// The Gateway API handlers call it after the request's API ID checks, so a
// create probes under the aggregator's final API ID and a request those
// checks reject never reaches an upstream.
//
// An update probes only the aggregated proxies the loaded aggregator does not
// already admit. One it admits keeps being served, or omitted, by the runtime
// on every tools/list, so a change such as a rename never fails because such a
// proxy has changed since it was admitted.
// already admit with the same alias and tool selection. One it admits keeps
// being served, or omitted, by the runtime on every tools/list, so a change
// such as a rename never fails because such a proxy has changed since it was
// admitted.
func (gw *Gateway) probeMCPAggregatorUpstreams(r *http.Request, mcpObj *oas.OAS) (string, int) {
if mcpObj == nil || mcpObj.GetTykExtension() == nil {
return "", 0
Expand Down Expand Up @@ -88,7 +91,7 @@ func (gw *Gateway) probeMCPAggregatorUpstreams(r *http.Request, mcpObj *oas.OAS)
if len(upstreams) == 0 {
return "", 0
}
return gw.validateMCPAggregatorUpstreamVersions(r, &APISpec{APIDefinition: &incoming}, refs, upstreams)
return gw.validateMCPAggregatorUpstreamViews(r, &APISpec{APIDefinition: &incoming}, refs, upstreams)
}

// admittedMCPAggregatorUpstreams returns the aggregated MCP proxies of the
Expand All @@ -114,10 +117,11 @@ func (gw *Gateway) admittedMCPAggregatorUpstreams(apiID, orgID string) map[strin
}

// mcpAggregatorUpstreamUnchanged reports whether the loaded aggregator already
// admits ref, so an update need not probe it again.
// admits ref under the same alias and tool selection, so an update need not
// probe it again: its selection and aggregated names were checked then.
func mcpAggregatorUpstreamUnchanged(admitted map[string]oas.TykMCPAggregatorUpstream, ref oas.TykMCPAggregatorUpstream) bool {
_, ok := admitted[ref.APIID]
return ok
previous, ok := admitted[ref.APIID]
return ok && previous.Alias == ref.Alias && slices.Equal(previous.Tools, ref.Tools)
}

// mcpAggregatorUpstreamStatus says whether an API can serve as an aggregated
Expand Down
48 changes: 42 additions & 6 deletions gateway/mcp_aggregator_call.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"errors"
"fmt"
"net/http"
"slices"
"strings"
"unicode/utf8"

"github.com/sirupsen/logrus"

Expand Down Expand Up @@ -138,7 +140,7 @@
return mcpaggregator.Upstream{}, "", errMCPAggregatorUnknownTool
}

if !mcpAggregatorSelects(upstream, tool) {
if !mcpAggregatorSelects(upstream, tool) || !mcpAggregatorNameFits(name) {
return upstream, "", errMCPAggregatorUnknownTool
}
if status := classifyMCPAggregatorUpstream(d.aggregator.OrgID, d.gw.getApiSpec(upstream.APIID)); status != mcpAggregatorUpstreamAdmitted {
Expand All @@ -148,11 +150,45 @@
}

// mcpAggregatorSelects reports whether the aggregator exposes tool of an
// aggregated MCP proxy. Every tool is exposed until tool selection (TT-18770)
// applies upstream.Tools here, rejecting deselected tools without an upstream
// call, and in listUpstreamTools.
func mcpAggregatorSelects(_ mcpaggregator.Upstream, _ string) bool {
return true
// aggregated MCP proxy: every tool when the proxy has no selection, otherwise
// only the selected names, matched exactly against the names the proxy
// exposes. tools/call applies it to one name, and tools/list applies the same

Check warning on line 155 in gateway/mcp_aggregator_call.go

View check run for this annotation

probelabs / Visor: architecture

performance Issue

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.
Raw output
For 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.
// rule through mcpAggregatorToolSelection, so a deselected tool is neither
// listed nor callable.
func mcpAggregatorSelects(upstream mcpaggregator.Upstream, tool string) bool {
return upstream.Tools == nil || slices.Contains(upstream.Tools, tool)
}

Check warning on line 161 in gateway/mcp_aggregator_call.go

View check run for this annotation

probelabs / Visor: performance

performance 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 the number of selected tools is often small, this 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.
Raw output
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`, improving performance for `tools/call` requests, especially those with many selected tools.
// mcpAggregatorToolSelection is an aggregated MCP proxy's tool selection as a
// set, for checking every tool of a tools/list in constant time. It is nil
// when the proxy has no selection.
type mcpAggregatorToolSelection map[string]struct{}

func newMCPAggregatorToolSelection(upstream mcpaggregator.Upstream) mcpAggregatorToolSelection {
if upstream.Tools == nil {
return nil
}
selection := make(mcpAggregatorToolSelection, len(upstream.Tools))
for _, tool := range upstream.Tools {
selection[tool] = struct{}{}
}
return selection
}

func (s mcpAggregatorToolSelection) selects(tool string) bool {
if s == nil {
return true
}
_, ok := s[tool]
return ok
}

// mcpAggregatorNameFits reports whether an aggregated tool name is within
// MCP's tool name limit. Admission rejects a configuration that would
// aggregate a longer name; the runtime also omits and refuses one, for a
// proxy that gains such a tool after the aggregator was admitted.
func mcpAggregatorNameFits(aggregatedName string) bool {
return utf8.RuneCountInString(aggregatedName) <= mcpaggregator.MaxToolNameLength
}

// isMCPUnknownToolError reports a proxy's unknown-tool rejection: -32602 with
Expand Down
18 changes: 18 additions & 0 deletions gateway/mcp_aggregator_catalogue_bound_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,24 @@ func TestMCPAggregatorToolsSize(t *testing.T) {
assert.Zero(t, mcpAggregatorToolsSize(nil))
}

func TestMCPAggregatorCatalogueToolLimitCountsOnlySelectedTools(t *testing.T) {
ts, github, ordersBackend := startMCPAggregatorRuntimeTest(t)
github.pager = pageToolNames(generatedToolNames(mcpAggregatorMaxCatalogueTools-1), 2500)
ts.Gw.LoadAPI(
ordersRESTSourceSpec(ordersBackend.URL, false),
ordersMCPProxyRuntimeSpec(),
githubMCPProxyRuntimeSpec(github.URL),
companyToolsRuntimeSpec(aggregated("orders-mcp", "orders"), selecting("github-mcp", "github", "tool_00042")),
)
hook := log.GetTestHook(t)

res := postModernToolsList(t, ts, "/company-tools/", companyToolsKey(t, ts))

require.Equal(t, http.StatusOK, res.status)
assert.Equal(t, []string{"github__tool_00042", "orders__create_order", "orders__list_orders"}, res.tools)
assert.Empty(t, mcpAggregatorOmissionWarnings(hook, "github-mcp"), "unselected tools do not count towards the catalogue limit")
}

// TestMCPAggregatorSharesTheCatalogueByteBudgetBetweenProxies configures 32
// aggregated proxies, 30 of them not loaded, so each proxy's share of the
// byte budget is 1 MiB. github-mcp serves two tools/list pages of one tool
Expand Down
11 changes: 0 additions & 11 deletions gateway/mcp_aggregator_dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
oteltrace "go.opentelemetry.io/otel/trace"

"github.com/TykTechnologies/tyk/internal/mcp"
mcpaggregator "github.com/TykTechnologies/tyk/internal/mcp/aggregator"
"github.com/TykTechnologies/tyk/request"
)

Expand Down Expand Up @@ -68,16 +67,6 @@
return nil
}

// call sends one modern-protocol JSON-RPC request to an aggregated MCP proxy
// and returns the raw JSON-RPC result.
func (d mcpAggregatorDispatcher) call(parent *http.Request, upstream mcpaggregator.Upstream, method string, params map[string]any) (json.RawMessage, error) {
spec, err := d.upstreamSpec(upstream.APIID)
if err != nil {
return nil, err
}
return d.send(parent, spec, method, params, d.loopTrust(spec))
}

// upstreamSpec returns the loaded spec of an aggregated MCP proxy this
// aggregator admits.
func (d mcpAggregatorDispatcher) upstreamSpec(apiID string) (*APISpec, error) {
Expand Down Expand Up @@ -217,7 +206,7 @@
// mcpAggregatorClientIPContext answers request.RealIP's context key with the
// client IP and every other key from the context it wraps.
type mcpAggregatorClientIPContext struct {
context.Context

Check warning on line 209 in gateway/mcp_aggregator_dispatch.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this 'context.Context' field and pass context as a parameter to methods that need it.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AaHpW9euLlYXYJrpFm1K&open=AaHpW9euLlYXYJrpFm1K&pullRequest=8905
clientIP string
}

Expand All @@ -232,7 +221,7 @@
// a timer of its own: the caller's context expiring is what cancels it, so
// the aggregated proxy's context is never done before the caller's.
type mcpAggregatorUpstreamDeadlineContext struct {
context.Context

Check warning on line 224 in gateway/mcp_aggregator_dispatch.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this 'context.Context' field and pass context as a parameter to methods that need it.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AaIP2bLJ3IFU4p7Cwsyp&open=AaIP2bLJ3IFU4p7Cwsyp&pullRequest=8905
deadline time.Time
}

Expand All @@ -254,7 +243,7 @@
// caller's context is done, with the caller's cause. The returned release
// function must be called once the aggregated proxy has answered.
func mcpAggregatorUpstreamRequestContext(parent context.Context, clientIP string) (context.Context, context.CancelFunc) {
base := oteltrace.ContextWithSpan(mcpAggregatorClientIPContext{Context: context.Background(), clientIP: clientIP}, oteltrace.SpanFromContext(parent))

Check warning on line 246 in gateway/mcp_aggregator_dispatch.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use the available context parameter 'parent' instead of creating a new background context.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AaIP2bLJ3IFU4p7Cwsyq&open=AaIP2bLJ3IFU4p7Cwsyq&pullRequest=8905
cancelCtx, cancel := context.WithCancelCause(base)
ctx := cancelCtx
if deadline, ok := parent.Deadline(); ok {
Expand Down
Loading
Loading